How can the object referencing feature in PHP be utilized to optimize the performance of dynamic menu generation from a database?

When generating dynamic menus from a database in PHP, utilizing object referencing can optimize performance by reducing the number of database queries needed to retrieve menu items. By storing retrieved menu items in an array with keys corresponding to their parent item IDs, subsequent queries can be avoided when building nested menus. This approach minimizes database interactions and improves the efficiency of menu generation.

// Assume $menuItems is an array of menu items retrieved from the database

// Create an empty array to store menu items with parent IDs as keys
$nestedMenuItems = [];

// Iterate through the menu items and store them in the nested array using parent IDs as keys
foreach ($menuItems as $menuItem) {
    $nestedMenuItems[$menuItem['parent_id']][] = $menuItem;
}

// Function to recursively build nested menus
function buildNestedMenu($items, $parentId = 0) {
    if (isset($items[$parentId])) {
        echo '<ul>';
        foreach ($items[$parentId] as $item) {
            echo '<li>' . $item['name'];
            buildNestedMenu($items, $item['id']);
            echo '</li>';
        }
        echo '</ul>';
    }
}

// Call the function to build the nested menu
buildNestedMenu($nestedMenuItems);