Recursive search in PHP array with path

前端 未结 1 907
清歌不尽
清歌不尽 2021-01-03 03:38

I have this haystack array:

$array = [
   [
      \"name\" => \"Intro\",
      \"id\" => \"123\",
      \"children\" => [
         \"name\" => \"         


        
相关标签:
1条回答
  • 2021-01-03 04:04

    I'll try to clean it up a bit, but this works:

    $needle = ["chapter one", 'foo', 'bar'];
    $array = [
        [
            "name" => "Intro",
            "id" => "123",
            "children" => [
                "name" => "foo",
                "id" => "234",
                "children" => [
                    "name" => "mur",
                    "id" => "445",
                ]
            ]
        ],[
            "name" => "chapter one",
            "id" => "9876",
            "children" => [
                "name" => "foo",
                "id" => "712",
                "children" => [
                    "name" => "bar",
                    "id" => "888",
                ]
            ]
        ]
    ];
    
    function searchTree($needle, $haystack, $strict=false) {
        if(!is_array($haystack)) {
            return false;
        }
        $match = false;
        if(array_keys($haystack) !== range(0, count($haystack) - 1) && !empty($needle)) {
            if(($strict && $haystack['name'] === $needle[0]) || (!$strict && $haystack['name'] == $needle[0])) {
                $match = true;
                array_shift($needle);
                if (!empty($needle)) {
                    return searchTree($needle, $haystack['children'], $strict);
                }
            }
        } else {
            foreach ($haystack as $key => $value) {
                if (is_array($value) && !empty($needle)) {
                    if (($strict && $value['name'] === $needle[0]) || (!$strict && $value['name'] == $needle[0])) {
                        $match = true;
                        array_shift($needle);
                        if (!empty($needle)) {
                            return searchTree($needle, $value['children'], $strict);
                        } else {
                            $haystack = $haystack[$key];
                        }
                    }
                }
            }
        }
        return (isset($haystack['id']) && $match) ? $haystack['id'] : false;
    }
    
    echo searchTree($needle, $array);
    

    output:

    888
    
    0 讨论(0)
提交回复
热议问题