List of arrays in PHP

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 add another array to the last array in my array list.

Getting this way 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'
            ],
        ]
    ]
];

Is there a function to make the job easier?

    
asked by anonymous 19.01.2018 / 01:18

1 answer

1

If the array is numeric and sequential indexes, you simply count the number 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 at Ideone | Repl.it

    
19.01.2018 / 01:26