note 114789 deleted from function.array-column by sobak
| From: | sobak@php.net | Date: | Tue, 01 Jul 2014 17:38:12 +0000 |
| Subject: | note 114789 deleted from function.array-column by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199802@lists.php.net to get a copy of this message | ||
Note Submitter: jakubplus at gmail dot com
----
This is somehow different from other approaches to satisfy needs of those not having a pleasure to
deal with PHP 5.
I've minimized need of using loops, so I use only one, to grab the whole array. Works fine with
additional parameter for returned key, empty or unelegant arrays:
$arr = array(
'director' => array(
'id' => 1,
'firstname' => 'Markus',
'lastname' => 'Tambis',
'age' => 43,
'height' => 180
),
'merchandise' => array(
'id' => 602,
'firstname' => 'Ronald',
'lastname' => 'Plus',
'age' => 43,
'height' => 180,
'city' => 'Berlin'
),
'sales' => array(
'id' => 55,
'firstname' => 'Veronica',
'lastname' => 'Ambit',
'city' => 'Warsaw'
),
array(
'id' => 4,
'firstname' => 'Trevor',
'lastname' => 'Howard',
'middlename' => 'Prover'
),
'anna'
);
function array_column(array $array, $returnvaluekey = null, $returnkey = null) {
if($returnvaluekey===null) {
return false;
}
$columns = array();
foreach($array as $key=>$value) {
if(!is_array($array[$key]) || empty($array[$key])) {
continue;
}
if($returnkey===null) {
if(isset($array[$key][$returnvaluekey])) {
$columns[] = $array[$key][$returnvaluekey];
}
}
else {
if(isset($array[$key][$returnkey]) && isset($array[$key][$returnvaluekey])) {
$columns[$array[$key][$returnkey]] = $array[$key][$returnvaluekey];
}
}
}
return $columns;
}
print_r(array_column($arr, 'middlename', 'firstname')); ...prints:
Array ( [Trevor] => Prover )