List of PHP arrays

Asked

Viewed 59 times

0

I have an array with several arrays inside

Ex:

$menus = [
    [0] => [
        'menu' => [
            'href' => '/product',
            'menu' => 'Produtos'
        ]
    ],
    [1] => [
        'menu' => [
            'href' => '/category',
            'menu' => 'Categorias'
        ]
    ],
    [2] => [
        'menu' => [
            'href' => '/user',
            'menu' => 'Usuários'
        ]
    ]
];

How can I include one more array in the last array in my array list.

Getting like this at the end

$menus = [
    [0] => [
        'menu' => [
            'href' => '/product',
            'menu' => 'Produtos'
        ]
    ],
    [1] => [
        'menu' => [
            'href' => '/category',
            'menu' => 'Categorias'
        ]
    ],
    [2] => [
        'menu' => [
            'href' => '/user',
            'menu' => 'Usuários'
        ],
        'submenu' => [
            'menu' => [
                'href' => '/user/list',
                'menu' => 'Todos Usuários'
            ],
        ]
    ]
];

There is a function to facilitate the work?

1 answer

1


If the array is of numerical and sequential indices, just you count the amount of elements and access the last position, which will be the quantity minus one.

$quantidade = count($menu);
$menu[$quantidade-1]['submenu'] = [
    'menu' => [
        'href' => '/user/list',
        'menu' => 'Todos Usuários'
    ]
];

Getting something like:

Array
(
    [0] => Array
        (
            [menu] => Array
                (
                    [href] => /product
                    [menu] => Produtos
                )

        )

    [1] => Array
        (
            [menu] => Array
                (
                    [href] => /category
                    [menu] => Categorias
                )

        )

    [2] => Array
        (
            [menu] => Array
                (
                    [href] => /user
                    [menu] => Usuários
                )

            [submenu] => Array
                (
                    [menu] => Array
                        (
                            [href] => /user/list
                            [menu] => Todos Usuários
                        )

                )

        )

)

See working on Ideone | Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.