Hướng dẫn
Quảng cáo

Hàm array_column() trong PHP

Hướng dẫn cách sử dụng hàm array_column() về mảng trong lập trình PHP

Tác dụng của hàm array_column()

The array_column() function return the values from a single column in the input array.

The following table summarizes the technical details of this function.

Return Value: Returns an array of values representing a single column from the input array.
Changelog: Since PHP 7.0.0, an array of objects can also be used.
Version: PHP 5.5.0+

Syntax

The basic syntax of the array_column() function is given with:

sort(array, column_key, index_key);

The following example shows the array_column() function in action.

 "1",
        "name" => "Titanic",
        "genre" => "Drama",
    ),
    array(
        "id" => "2",
        "name" => "Justice League",
        "genre" => "Action",
    ),
    array(
        "id" => "3",
        "name" => "Joker",
        "genre" => "Thriller",
    )
);

// Getting the column of names
$names = array_column($movies, "name");
print_r($names);
?>

Parameters

The array_column() function accepts the following parameters.

Parameter Description
array Required. Specifies a multi-dimensional array or an array of objects to work on.
column_key

Required. Specifies the index or key name of the column you want to retrieve.

This parameter can also be NULL to return complete arrays or objects (this is useful together with the index_key parameter to reindex the array).
index_key Optional. Specifies the column to use as the index/keys for the returned array.

More Examples

Here're some more examples showing how array_column() function actually works:

The following example demonstrates how to retrieve the "name" column values from the movies array indexed by the "id" column values. You can choose any column for indexing purpose.

 "1",
        "name" => "Titanic",
        "genre" => "Drama",
    ),
    array(
        "id" => "2",
        "name" => "Justice League",
        "genre" => "Action",
    ),
    array(
        "id" => "3",
        "name" => "Joker",
        "genre" => "Thriller",
    )
);

// Getting the column of names
$names = array_column($movies, "name", "id");
print_r($names);
?>

The following example get the column of names from the public "name" property of an object.

name = $name;
    }
}

// Creating the array of objects
$persons = [
    new Person("Peter"),
    new Person("Alice"),
    new Person("Clark"),
];

// Getting the column of names
$names = array_column($persons, "name");
print_r($names);
?>

 

 

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements