在多维树状数组中查找键的路径 [英] find path of a key in a multi-dimensional tree-like array
本文介绍了在多维树状数组中查找键的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我有这个数组(实际的数组可以是多层深度并跨越树结构)
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
现在,例如我想要键 7
的路径,它可以像这样显示:
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
有人可以帮我实现这样的递归函数吗?
推荐答案
这将返回您正在寻找的内容.如果没有找到key,它将返回null.
This will return you what you are looking for. It will return null if the key is not found.
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;
}
这篇关于在多维树状数组中查找键的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文