How can PHP arrays be filled recursively for a navigation structure?

To fill PHP arrays recursively for a navigation structure, you can create a function that iterates through the navigation data and adds subitems as arrays within the parent item. This can be achieved by using a recursive function that checks if an item has subitems and calls itself to add them.

<?php

// Sample navigation data
$navigation = [
    [
        'title' => 'Home',
        'url' => '/home',
    ],
    [
        'title' => 'Products',
        'url' => '/products',
        'subitems' => [
            [
                'title' => 'Product A',
                'url' => '/products/a',
            ],
            [
                'title' => 'Product B',
                'url' => '/products/b',
                'subitems' => [
                    [
                        'title' => 'Subproduct X',
                        'url' => '/products/b/x',
                    ],
                    [
                        'title' => 'Subproduct Y',
                        'url' => '/products/b/y',
                    ],
                ],
            ],
        ],
    ],
];

// Function to fill arrays recursively
function fillNavigation(&$navItems) {
    foreach ($navItems as &$item) {
        if (isset($item['subitems'])) {
            fillNavigation($item['subitems']);
        }
    }
}

// Fill the navigation array recursively
fillNavigation($navigation);

// Output the filled navigation array
print_r($navigation);

?>