How can PHP developers efficiently handle the swapping of menu items at different levels of depth within a nested menu structure?
When swapping menu items at different levels of depth within a nested menu structure, PHP developers can efficiently handle this by recursively traversing the menu structure and swapping the desired items based on their depth levels.
function swapMenuItems(&$menu, $item1, $item2, $depth = 0) {
foreach ($menu as &$item) {
if ($item['id'] == $item1['id']) {
$item = $item2;
} else if ($item['id'] == $item2['id']) {
$item = $item1;
}
if (isset($item['children'])) {
swapMenuItems($item['children'], $item1, $item2, $depth + 1);
}
}
}
// Usage example
$menu = [
['id' => 1, 'name' => 'Home'],
['id' => 2, 'name' => 'Products', 'children' => [
['id' => 3, 'name' => 'Laptops'],
['id' => 4, 'name' => 'Desktops'],
]],
];
$item1 = ['id' => 3, 'name' => 'Laptops'];
$item2 = ['id' => 4, 'name' => 'Desktops'];
swapMenuItems($menu, $item1, $item2);
print_r($menu);