find path of a key in a multi-dimensional tree-like array

↘锁芯ラ 提交于 2019-12-24 01:41:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!