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' => array(
'id1' => 0,
'foo' => 1,
'fs2' => array(
'id2' => 1,
'foo2' => 2,
'fs3' => array(
'id3' => null,
),
'fs4' => array(
'id4' => 4,
'bar' => 1,
),
),
),
);
search($array, 'fs3'); // Returns ('fs1.fs2.fs3', array('id3' => null))
search($array, 'fs2'); // Returns ('fs1.fs2', array('id2' => 1, ... ))
I've been able to recurse through the array to find the correct key and return the data using RecursiveArrayIterator
(shown below), but I don't know the best way to keep track of what path I'm currently on.
$i = new RecursiveIteratorIterator
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($i as $key => value) {
if ($key === $search) {
return $value;
}
}