问题
hey, I have this array (the actual array can be several level deeps and spans a tree-structure)
array
3 =>
array
4 =>
array
7 => null
8 => null
5 => null
6 => null
Now, e.g. I want the path to key 7, it can be shown like this:
array
0 => int 7
1 => int 4
2 => int 3
Can someone help me with such a recursion function?
回答1:
This will return you what you are looking for. It will return null if the key is not found.
In codepad.
function getkeypath($arr, $lookup)
{
if (array_key_exists($lookup, $arr))
{
return array($lookup);
}
else
{
foreach ($arr as $key => $subarr)
{
if (is_array($subarr))
{
$ret = getkeypath($subarr, $lookup);
if ($ret)
{
$ret[] = $key;
return $ret;
}
}
}
}
return null;
}
来源:https://stackoverflow.com/questions/4381352/find-path-of-a-key-in-a-multi-dimensional-tree-like-array