PHP push values to nested array

Viewed 330

i have the created the following object array in php

$treeData[] = (object) array(
    "name"=> "A",
    "children" => [
        [
            "name"=> "A1", 
            "children"=> [ 
                [ 
                    "name"=> "A1.1",
                    "children"=> [ 
                        [
                            "name"=> "A1.1.1",
                            "children"=> [ 
                                ....

I'm trying to push new values inside the children of A1.1.1 based on below condition:

foreach ($treeData as $value) {
    if ($value->name == 'A') {
        $value->name[][] = (object) array(
                                           "name"=> "ChildA", 
                                           "children"=> ""
                                    );
        break;
    }
}

But it's giving me an error

Expected result should match as below example:

$treeData[] = (object) array(
    "name"=> "A",
    "children" => [
        [
            "name"=> "A1",
            "children"=> [ [
                "name"=> "A1.1",
                "children"=> [ [
                    "name"=> "A1.1.1",
                    "children"=> [ 
                        [
                            "name"=> "ChildA",
                            "children"=> [ [ 
                                "name"=> "ChildA1"
                            ] ]
                        ],
                        [
                            "name"=> "ChildA",
                            "children"=> [ [
                                "name"=> "ChildA2"
                            ] ]
                        ],
                    ]
                ] ]
            ] ]
        ]
   ]);   

What I'm doing wrong here or any way to achieve this in different approach

The error I'm getting:

"Fatal error: Uncaught Error: [] operator not supported for strings "

1 Answers

First of all you getting the error as you do: $value->name[][]. Notice the name is a string so you ccannot use [] (array append operator) on it.

I would have take the recursive approach if I were you. Consider the following pseudo code:

function addChild($root, $addToName, $nameToAdd) {
    if ($root->name == $addToName)
        $root->children[] =  (object) array("name"=> $nameToAdd, "children"=> []);
    else 
        foreach($root->children as $child)
            addChild($child, $addToName, $nameToAdd);
}  

And now call is with: addChild($treeData, 'A', "ChildA")

Related