How can PHP be used to efficiently handle the logic of assigning child nodes to parent nodes in a dynamic menu?

To efficiently handle the logic of assigning child nodes to parent nodes in a dynamic menu using PHP, you can organize your menu items in an array where each item has an 'id' and 'parent_id' field. By iterating through the array and grouping child nodes under their respective parent nodes, you can easily build a hierarchical menu structure.

$menuItems = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'Home'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'About'],
    ['id' => 3, 'parent_id' => 2, 'name' => 'Team'],
    ['id' => 4, 'parent_id' => 2, 'name' => 'History'],
    ['id' => 5, 'parent_id' => 0, 'name' => 'Services'],
];

$menu = [];
foreach ($menuItems as $item) {
    $menu[$item['parent_id']][] = $item;
}

function buildMenu($menu, $parent_id = 0) {
    $html = '';
    if (isset($menu[$parent_id])) {
        $html .= '<ul>';
        foreach ($menu[$parent_id] as $item) {
            $html .= '<li>' . $item['name'];
            $html .= buildMenu($menu, $item['id']);
            $html .= '</li>';
        }
        $html .= '</ul>';
    }
    return $html;
}

echo buildMenu($menu);