How to count the number of dynamic nested arrays in laravel dynamically

Viewed 155
{
    "name" : "lv0",
    "children" : [
       {
           "name" : "lv1",
           "children" : [
                {
                    "name" : "lv2",
                    "children" : [
                        {
                            "name" : "lv3"
                        }
                    ]
                }
            ]
       }
    ]
}

this is the json and I only wants to count the number of children's array, I am using this code:

$data[] = $request->children;
    $count = 0;
    foreach($data as $data){
        $count++;
    }
    return $count;
1 Answers

Since you don't know how many nested children, you should use while loop:

$data = json_decode('{
    "name" : "lv0",
    "children" : [
       {
           "name" : "lv1",
           "children" : [
                {
                    "name" : "lv2",
                    "children" : [
                        {
                            "name" : "lv3"
                        }
                    ]
                }
            ]
       }
    ]
}');
$child = $data;
$count = 0;
while (property_exists($child, 'children')) {
    $count++;
    $child = $child->children[0];
}
echo $count;

Ouput:

3
Related