note 129083 added to function.array-column
| From: | Rumour at main dot php dot net | Date: | Sat, 02 Dec 2023 19:46:02 +0000 |
| Subject: | note 129083 added to function.array-column | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221037@lists.php.net to get a copy of this message | ||
If you want to preserve the array keys AND you want it to work on both object properties and array
elements AND you want it to work if some of the arrays/objects in the array do not have the given
key/property defined, basically the most ROBUST version you can get, yet quick enough:
<?php
function array_column_keys(array|ArrayAccess $arr, string $col) {
// like array_columns but keeps the keys
//to make it work for objects and arrays
return array_map(fn($e) => (is_countable($e) ? ($e[$col]??null) : null) ?: (is_object($e) ?
$e->$col : null), $arr);
}
?>
If a key/property is undefined, the value in the result array will be NULL. You can use
array_filter() to filter those out if needed.
<?php
class a {
public string $a = 'property a';
public string $b = 'property b';
}
$a1 = new a;
$a2 = new a;
$a2->a = 'plop';
$b = ['one'=> ['a'=>'plop'],
3 => $a1,
4 => $a2,
5 =>[],
'kud'=>new a];
return array_column_keys($b, 'a');
?>
Returns:
Array
(
[one] => plop
[3] => property a
[4] => something else
[5] =>
[kud] => property a
)
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 85.145.75.206)
----
Manual Page -- https://php.net/manual/en/function.array-column.php
Edit -- https://main.php.net/note/edit/129083
Del: integrated -- https://main.php.net/note/delete/129083/integrated
Del: useless -- https://main.php.net/note/delete/129083/useless
Del: bad code -- https://main.php.net/note/delete/129083/bad+code
Del: spam -- https://main.php.net/note/delete/129083/spam
Del: non-english -- https://main.php.net/note/delete/129083/non-english
Del: in docs -- https://main.php.net/note/delete/129083/in+docs
Del: other reasons-- https://main.php.net/note/delete/129083
Reject -- https://main.php.net/note/reject/129083
Search -- https://main.php.net/manage/user-notes.php