note 114789 added to function.array-column

From: Date: Mon, 07 Apr 2014 10:51:38 +0000
Subject: note 114789 added to function.array-column
Groups: php.notes 
Request: Send a blank email to php-notes+get-199204@lists.php.net to get a copy of this message
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 ) ---- Server IP: 46.17.113.2 Probable Submitter: 178.36.216.83 ---- Manual Page -- http://php.net/manual/en/function.array-column.php Edit -- https://master.php.net/note/edit/114789 Del: integrated -- https://master.php.net/note/delete/114789/integrated Del: useless -- https://master.php.net/note/delete/114789/useless Del: bad code -- https://master.php.net/note/delete/114789/bad+code Del: spam -- https://master.php.net/note/delete/114789/spam Del: non-english -- https://master.php.net/note/delete/114789/non-english Del: in docs -- https://master.php.net/note/delete/114789/in+docs Del: other reasons-- https://master.php.net/note/delete/114789 Reject -- https://master.php.net/note/reject/114789 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199204) next »