1
{
    "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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

15 Comments

it is working but $data = json_decode('{ "name" : "lv0", "children" : [ { "name" : "lv1", "children" : [ { "name" : "lv2", "children" : [ { "name" : "lv3" } ] } ] } ] }'); this part is not for me how can i do this for request case?
Since I don't know what your input looks like, I have assumed $data according to your question using json_decode
inputs are the same as provided in json
If the data in your request is already an object, just replace it for $data
public function createTree($request) { // this is the function }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.