note 127046 added to function.array-column
| From: | oleg dot bolden at gmail dot com | Date: | Wed, 11 May 2022 14:38:33 +0000 |
| Subject: | note 127046 added to function.array-column | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-218371@lists.php.net to get a copy of this message | ||
Index_key is safely applicable only in cases when corresponding values of this index are unique
through over the array. Otherwise only the latest element of the array with the same index_key value
will be picked up.
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
'company_id' => 1,
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
'company_id' => 1,
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
'company_id' => 1,
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
'company_id' => 2,
)
);
$first_names = array_column($records, 'first_name', 'company_id');
print_r($first_names);
?>
The above example will output:
<?php
Array
(
[1] => Jane
[2] => Peter
)
?>
To group values by the same
index_key in arrays one can use simple replacement for the
array_column like below example function:
<?php
function arrayed_column(array $array, int|string $column_key, int|string $index_key) {
$output = [];
foreach ($array as $item) {
$output[$item['index_key']][] = $item['column_key'];
}
return $output;
}
$first_names = arrayed_column($records, 'first_name', 'company_id');
print_r($first_names);
?>
The output:
<?php
Array
(
[1] => Array
(
[0] => John
[1] => Sally
[2] => Jane
)
[2] => Array
(
[0] =>Peter
)
)
?>
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.47 (proxied: 46.242.11.95)
----
Manual Page -- https://php.net/manual/en/function.array-column.php
Edit -- https://main.php.net/note/edit/127046
Del: integrated -- https://main.php.net/note/delete/127046/integrated
Del: useless -- https://main.php.net/note/delete/127046/useless
Del: bad code -- https://main.php.net/note/delete/127046/bad+code
Del: spam -- https://main.php.net/note/delete/127046/spam
Del: non-english -- https://main.php.net/note/delete/127046/non-english
Del: in docs -- https://main.php.net/note/delete/127046/in+docs
Del: other reasons-- https://main.php.net/note/delete/127046
Reject -- https://main.php.net/note/reject/127046
Search -- https://main.php.net/manage/user-notes.php