note 82256 deleted from function.array-map by cmb
| From: | cmb@php.net | Date: | Sun, 25 Aug 2019 09:11:22 +0000 |
| Subject: | note 82256 deleted from function.array-map by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212002@lists.php.net to get a copy of this message | ||
Note Submitter: moester at gmail dot com
----
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)
?>