bajaklaut201180
bajaklaut201180

Reputation: 5

Foreach Array error (PHP)

I want to create dynamic menu with looping an array be 1 object menu. But error occured. Our code is below it:

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

I get error notif, "Indirect modification of overloaded element of App\Menu has no effect"

Please Help me :)

Upvotes: 0

Views: 113

Answers (2)

overals
overals

Reputation: 92

You have a broken array, something like an incorrect conversion of json to an array;

You can test(execute) it here (working example)

Upvotes: 0

Mike Foxtech
Mike Foxtech

Reputation: 1651

The code is working. You have a lot of bugs in your arrays.

Fixed:

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

Upvotes: 3

Related Questions