note 103905 added to function.array-values
| From: | abimaelrc at osu1 dot php dot net | Date: | Tue, 10 May 2011 12:39:02 +0000 |
| Subject: | note 103905 added to function.array-values | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179580@lists.php.net to get a copy of this message | ||
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
* Get all values from specific key in a multidimensional array
*
* @param $key string
* @param $arr array
* @return null|string|array
*/
function array_value_recursive($key, array $arr){
$val = array();
array_walk_recursive($arr, function($v, $k) use($key, &$val){
if($k == $key) array_push($val, $v);
});
return count($val) > 1 ? $val : array_pop($val);
}
$arr = array(
'foo' => 'foo',
'bar' => array(
'baz' => 'baz',
'candy' => 'candy',
'vegetable' => array(
'carrot' => 'carrot',
)
),
'vegetable' => array(
'carrot' => 'carrot2',
),
'fruits' => 'fruits',
);
var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6)
"carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
----
Server IP: 69.147.83.197
Probable Submitter: 64.237.177.99
----
Manual Page -- http://www.php.net/manual/en/function.array-values.php
Edit -- https://master.php.net/note/edit/103905
Del: integrated -- https://master.php.net/note/delete/103905/integrated
Del: useless -- https://master.php.net/note/delete/103905/useless
Del: bad code -- https://master.php.net/note/delete/103905/bad+code
Del: spam -- https://master.php.net/note/delete/103905/spam
Del: non-english -- https://master.php.net/note/delete/103905/non-english
Del: in docs -- https://master.php.net/note/delete/103905/in+docs
Del: other reasons-- https://master.php.net/note/delete/103905
Reject -- https://master.php.net/note/reject/103905
Search -- https://master.php.net/manage/user-notes.php