Foreach数组错误(PHP)

时间:2018-04-12 11:01:15

标签: php arrays laravel foreach

我想创建动态菜单,循环数组为1个对象菜单。但是发生了错误。 我们的代码低于它:

$menus = [{"id" => 1, "label" => "content", "parent_id" => 0},{"id" => 2, "label" => "inbox", "id" => 3, "parent_id" => 0}, {"id" => 4, "label" => "item", "parent_id" => 0}];
$sub_menus = [{"id" => 5, "label" => "banner", "parent_id" => 1},{"id" => 6, "label" => "ads", "parent_id" => 1}];

foreach($menus as $row => $value){
    $nav[$row] = $value;
    foreach($sub_menus as $r => $v) {
        if($v['parent_id'] == $value['id']){
            $nav[$row]['sub_menu'][$r] = $v;
        }
     }
 }

我收到错误通知,“间接修改App \ Menu的重载元素无效

请帮帮我:)。

2 个答案:

答案 0 :(得分:3)

代码正在运行。您的阵列中有很多错误。

<强>固定

$menus = [
            [
                "id" => 1,
                "label" => "content",
                "parent_id" => 0
            ],
            [
                "id" => 2,
                "label" => "inbox",
                "parent_id" => 0
            ],
            [
                "id" => 4,
                "label" => "item",
                "parent_id" => 0
            ]
        ];

        $sub_menus = [
            [
                "id" => 5,
                "label" => "banner",
                "parent_id" => 1
            ],
            [
                "id" => 6,
                "label" => "ads",
                "parent_id" => 1
            ]
        ];

        foreach($menus as $row => $value){
            $nav[$row] = $value;
            foreach($sub_menus as $r => $v) {
                if($v['parent_id'] == $value['id']){
                    $nav[$row]['sub_menu'][$r] = $v;
                }
            }
        }

答案 1 :(得分:0)

你有一个破碎的数组,比如json到数组的错误转换;

你可以测试(执行)它here(工作示例)