Searching for key in multidimensional array and returning path to it

后端 未结 4 918
日久生厌
日久生厌 2021-01-06 12:48

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\' =>         


        
4条回答
  •  心在旅途
    2021-01-06 13:37

    It looks like you are assuming the keys will always be unique. I do not assume that. So, your function must return multiple values. What I would do is simply write a recursive function:

    function search($array, $key, $path='')
    {
        foreach($array as $k=>$v)
        {
            if($k == $key) yield array($path==''?$k:$path.'.'.$k, array($k=>$v));
            if(is_array($v))
            { // I don't know a better way to do the following...
                $gen = search($v, $key, $path==''?$k:$path.'.'.$k);
                foreach($gen as $v) yield($v);
            }
        }
    }
    

    This is a recursive generator. It returns a generator, containing all hits. It is used very much like an array:

    $gen = search($array, 'fs3');
    foreach($gen as $ret)
        print_r($ret); // Prints out each answer from the generator
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题