简体   繁体   English

使用PHP从JSON获取父级和子级深度级别?

[英]Get Parent and Child depth level from JSON using PHP?

I have a tree structure like this 我有这样的树状结构

树状结构

and get JSON value like this 然后像这样获取JSON值

[{"id":1,"children":[{"id":3,"children":[{"id":9,"children":[{"id":8}]}]}]},{"id":10,"children":[{"id":11,"children":[{"id":13}]},{"id":12}]}]

I need to find the child depth level and parent id of that child from this JSON using PHP. 我需要使用PHP从此JSON中找到子级的子级和父级ID。

So i want output will be like this 所以我想输出会像这样

id=>1, parent_id=>0, level=>0
id=>3, parent_id=>1, level=>1
id=>9, parent_id=>3, level=>2
id=>8, parent_id=>9, level=>3
id=>10, parent_id=>0, level=>0
id=>11, parent_id=>10, level=>1
id=>13, parent_id=>11, level=>2
id=>12, parent_id=>10, level=>1

Thanks 谢谢

Try something like this: 尝试这样的事情:

$jsonString = '[{"id":1,"children":[{"id":3,"children":[{"id":9,"children":[{"id":8}]}]}]},{"id":10,"children":[{"id":11,"children":[{"id":13}]},{"id":12}]}]';
$jsonArray = json_decode($jsonString);

function read_tree_recursively($items, $parent_id = 0, $result = array(), $level = 0) {
    foreach($items as $child) {
        $result[$child->id] = array(
            'id' => $child->id,
            'parent_id' => $parent_id,
            'level' => $level
        );

        if (!empty($child->children)) {
            $result = read_tree_recursively($child->children, $child->id, $result, $level+1);
        }
    }
    return $result;
}

// usage
read_tree_recursively($jsonArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM