PHP将值推送到嵌套数组

时间:2019-06-06 02:38:04

标签: php arrays object

我已经在php中创建了以下对象数组

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

我正在尝试根据以下条件在A1.1.1的子级中推送新值:

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

但这给我一个错误

预期结果应符合以下示例:

$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"
                            ] ]
                        ],
                    ]
                ] ]
            ] ]
        ]
   ]);   

我在这里做错了什么,或者以其他方式实现此目的的任何方式

我得到的错误:

  

“致命错误:未捕获错误:字符串不支持[]运算符”

1 个答案:

答案 0 :(得分:2)

首先,您在执行操作时遇到错误:$value->name[][]。请注意,该名称是一个字符串,因此您无法在其上使用[](数组追加运算符)。

如果我是你,我将采用递归方法。考虑以下伪代码:

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

现在呼叫与:addChild($treeData, 'A', "ChildA")