PHP: 如何在树状 JSON 结构中递归搜索 ID 和 return 包含所有先前 ID 的路径

PHP: How to search for an ID in a tree-like JSON structure recursively and return the path including all previous IDs

我有一个我无法处理的具体问题。 我有一个 JSON 文件,我需要在其中找到 ID。 当找到 id 时,我需要获取所有以前的 id。

找到 id 51。 结果:51、12962、1101、1100

预先感谢您的帮助。

{
"status":"SUCCESS",
"data":[
    {
        "id":"12522",
        "name":"name 1",
    },
    {
        "id":"13081",
        "name":"name 2",
    },
    {
        "id":"1100",
        "name":"name 3",
        "childs":[
            {
                "id":"11591",
                "name":"name 4",
                "childs":[
                    {
                        "id":"12382",
                        "name":"name 5",
                    },
                    {
                        "id":"48",
                        "name":"name 6",
                    },
                    {
                        "id":"11590",
                        "name":"name 7",
                    }
                ]
            },
            {
                "id":"1101",
                "name":"name 8",
                "childs":[
                    {
                        "id":"11589",
                        "name":"name 9",
                    },
                    {
                        "id":"12962",
                        "name":"name 10",
                        "childs":[
                            {
                                "id":"51",
                                "name":"name 11",
                            }
                        ]
                    }
                ]
            }

.....

我已经删除了这个示例的 JSON 输入,但结果是一个数组,其中包含直到您要查找的 ID 为止的 ID(如果未找到该 ID,则为空) ).代码带有注释,因此您可以看到它实际做了什么。基本上,我使用的是递归函数,即调用自身的函数,在每次调用时传递当前的 ID 堆栈。

<?php
$data = json_decode( '[{"id": "1234"},{"id": "4567"},{"id": "1100","childs": [{"id": "7890"},{"id": "1101","childs": [{"id": "12962","childs": [{"id": "51"}]}]}]}]' );

// recursively go through the data, searching for the id
function findIdRecursive( $id, $data, $stack = array() ) {
    foreach ( $data as $d ) {
        // this object corresponds to the id
        if ( $d->id === $id ) {
            $stack[] = $id;
            break;
        } else if ( isset( $d->childs ) ) {
            // recursively go through this object's children
            $childStack = findIdRecursive( $id, $d->childs, $stack );
            if( in_array( $id, $childStack ) ) {
                // if the id is present in the child stack, return this path
                $stack = array_merge( [ $d->id ], $childStack );
                break;
            }
        }
    }

    return $stack;
}

// [ 51, 12962, 1101, 1100 ]
var_dump( array_reverse( findIdRecursive( "51", $data ) ) );