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

时间:2014-11-05 07:13:38

标签: php json

我有像这样的树结构

Tree Structure

并获得像这样的JSON值

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

我需要使用PHP从这个JSON中找到该子项的子深度级别和父ID。

所以我希望输出会像这样

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

由于

1 个答案:

答案 0 :(得分:3)

尝试这样的事情:

$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);