https://www.php.net/manual/en/function.array-column.php
array_column ( array $array
, int|string|null $column_key
, int|string|null $index_key
= null
) : array
// Example with $column key but null $index_key (only values of $column key will be returned)
<?php
// Array representing a possible record set returned from a database
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$first_names = array_column($records, 'first_name');
print_r($first_names);
?>
The above example will output:
Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )
// Example witth $column_key and $index_key, returned $index_key will become key and $value of $column_key will become value
<?php
// Using the $records array from Example #1
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>
The above example will output:
Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )
// Example with $index key but null $column_key(everything will be returned)
array_column($array,null,'house'), with
$array = [
[
'name' =>'Bob',
'house' =>'big',
],
[
'name' =>'Alice',
'house' =>'small',
],
[
'name' =>'Jack',
'house' => null,
],
];
var_dump(array_column($array,null,'house'));
On 5.6.30, 7.0.0, 7.2.0 (not limited to) get the following results
array(3) {
["big"]=>
array(2) {
["name"]=>
string(3) "Bob"
["house"]=>
string(3) "big"
}
["small"]=>
array(2) {
["name"]=>
string(5) "Alice"
["house"]=>
string(5) "small"
}
[0]=>
array(2) {
["name"]=>
string(4) "Jack"
["house"]=>
NULL
}
}
No comments:
Post a Comment