Here's my solution:
function find_value_by_key($key,$array) {
$data = array('key'=>$key,'ret'=>array());
array_walk_recursive($array,function($v,$k) use (&$data) {
if ($k==$data['key'])
$data['ret'][] = $v;
},$data);
return $data['ret'];
}
Returns an array of the value(s) found, if the key isn't found then an empty array is returned.
If you only need to return the first value it finds you can use:
function find_value_by_key($key,$array) {
$data = array('key'=>$key);
array_walk_recursive($array,function($v,$k) use (&$data) {
if (isset($data['ret']))
return;
if ($k==$data['key'])
$data['ret'] = $v;
},$data);
return $data['ret']?:false;
}
Returns the first value found.
If the key isn't found then false
is returned.
Example with the following array:
$array = array(
0 => 'A',
1 => 'B',
2 => 'C',
'foo' => 'bar',
'mykey' => 'haha',
'test' => array(
'example' => 'lol',
'mykey' => 'hoho',
),
'random' => array(
array(
'mykey' => 'hehe',
'notmykey' => 'topkek',
),
array(
'mykey' => 'huhu',
'notmykey' => 'topkek',
),
), );
First function would return ["haha","hoho","hehe","huhu"]
, second one would return "haha"