RaGu
RaGu

Reputation: 683

Get Parent and Child depth level from JSON using PHP?

I have a tree structure like this

Tree Structure

and get JSON value like this

[{"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.

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

Upvotes: 0

Views: 1948

Answers (1)

makhov
makhov

Reputation: 450

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

Upvotes: 4

Related Questions