note 82256 added to function.array-map
| From: | moester at gmail dot com | Date: | Wed, 02 Apr 2008 21:21:38 +0000 |
| Subject: | note 82256 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137871@lists.php.net to get a copy of this message | ||
Wish this was built in. Mimics Ruby and Prototype's array pluck function. Returns specific
key/column from an array of objects.
<?php
function array_pluck($key, $array)
{
if (is_array($key) || !is_array($array)) return array();
$funct = create_function('$e', 'return is_array($e) &&
array_key_exists("'.$key.'",$e) ? $e["'. $key .'"] :
null;');
return array_map($funct, $array);
}
// usage:
$a = array(array("id"=>10, "name"=>"joe"),
array("id"=>11, "name"=>"bob"));
$ids = array_pluck("id", $a); // == array(10,11)
$names = array_pluck("name", $a); // == array("joe", "bob")
//works on non-keyed arrays also:
$a = array(array(3,4), array(5,6));
$col2 = array_pluck(1,$a); // == array(4,6) (grab 2nd column of data)
?>
----
Server IP: 209.41.74.194
Probable Submitter: 64.81.48.166
----
Manual Page -- http://www.php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/82256
Del: integrated -- https://master.php.net/note/delete/82256/integrated
Del: useless -- https://master.php.net/note/delete/82256/useless
Del: bad code -- https://master.php.net/note/delete/82256/bad+code
Del: spam -- https://master.php.net/note/delete/82256/spam
Del: non-english -- https://master.php.net/note/delete/82256/non-english
Del: in docs -- https://master.php.net/note/delete/82256/in+docs
Del: other reasons-- https://master.php.net/note/delete/82256
Reject -- https://master.php.net/note/reject/82256
Search -- https://master.php.net/manage/user-notes.php