I need to find a specific key in an array, and return both its value and the path to find that key. Example:
$array = array(
\'fs1\' =>
Just for completion sake and future visitors. Combining the example code above and the answer I commented about to get the keys. Here is a working function that will return the requested results with one small change. In my return array I return the keys path
and value
instead of the requested 0
and $search
for the keys. I find this more verbose and easier to handle.
array(
'id1' => 0,
'foo' => 1,
'fs2' => array(
'id2' => 1,
'foo2' => 2,
'fs3' => array(
'id3' => null,
),
'fs4' => array(
'id4' => 4,
'bar' => 1,
),
),
),
);
function search($array, $searchKey=''){
//create a recursive iterator to loop over the array recursively
$iter = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST);
//loop over the iterator
foreach ($iter as $key => $value) {
//if the key matches our search
if ($key === $searchKey) {
//add the current key
$keys = array($key);
//loop up the recursive chain
for($i=$iter->getDepth()-1;$i>=0;$i--){
//add each parent key
array_unshift($keys, $iter->getSubIterator($i)->key());
}
//return our output array
return array('path'=>implode('.', $keys), 'value'=>$value);
}
}
//return false if not found
return false;
}
$searchResult1 = search($array, 'fs2');
$searchResult2 = search($array, 'fs3');
echo "";
print_r($searchResult1);
print_r($searchResult2);
outputs:
Array
(
[path] => fs1.fs2
[value] => Array
(
[id2] => 1
[foo2] => 2
[fs3] => Array
(
[id3] =>
)
[fs4] => Array
(
[id4] => 4
[bar] => 1
)
)
)
Array
(
[path] => fs1.fs2.fs3
[value] => Array
(
[id3] =>
)
)