John Davidson

arrays - PHP - Remove empty menus

0 comments
Message:


Good afternoon guys, I'm having a hard time finding the solution to this simple problem, I hope someone can help me.


I have a recursive array automatically generated by the source code, I use this array as the system's menu tree, however, it goes through a permission system, and some submenus are excluded, leaving certain menus empty, follow the example in JSON:


{
"1": {
"id": 1,
"idFather": null,
"nome": "test 1",
"sub": {
"4": {
"id": 4,
"idFather": 1,
"nome": "test 1.1",
"sub": {}
},
"5": {
"id": 5,
"idFather": 1,
"nome": "test 1.2",
"sub": {
"7": {
"id": 7,
"idFather": 5,
"nome": "test 1.3.1",
"sub": {}
},
"8": {
"id": 8,
"idFather": 5,
"nome": "test 1.3.2",
"sub": {}
}
}
},
"6": {
"id": 6,
"idFather": 1,
"nome": "test 1.3"
}
}
},
"2": {
"id": 2,
"idFather": null,
"nome": "test 2"
},
"3": {
"id": 3,
"idFather": null,
"nome": "test 3",
"sub": {
"10": {
"id": 10,
"idFather": 3,
"nome": "test 3.2"
}
}
}
}

Within key 1 I have key 4 with no other items, and I have key 5 with two keys (7 and 8), however, these 2 keys also do not contain items, so I need to remove keys 4, 7, 8 and consequently, key 5 too, as it will be empty at the end of the removals!
Note that key 6 inside key 1, key 10 inside key 3 and key 2 do not contain the "sub" element, so it must not be removed!


I am Brazilian, so my English may be a little rusty.



My Answer:
"menu": [
{
"name": "Home",
"url": "/home",
"submenus": []
},
{
"name": "Products",
"url": "/products",
"submenus": [
{
"name": "Electronics",
"url": "/electronics",
"submenus": []
},
{
"name": "Clothing",
"url": "/clothing",
"submenus": []
}
]
},
{
"name": "Services",
"url": "/services",
"submenus": []
}
]
}

_As you can see, the "Products" menu has submenus, but "Clothing" and "Electronics" are empty. I need to remove these empty submenus from the array. Here's how you can achieve this in PHP:_

php
function removeEmptyMenus($menu) {
foreach ($menu as $key => $item) {
if (empty($item['submenus'])) {
unset($menu[$key]);
} else {
$menu[$key]['submenus'] = removeEmptyMenus($item['submenus']);
}
}
return array_values($menu);
}

$menu = json_decode($json, true);
$menu = removeEmptyMenus($menu);
echo json_encode($menu);


_This code defines a recursive function `removeEmptyMenus` that iterates over the menu items and removes any empty submenus. It then returns the modified menu array without the empty submenus. Finally, it encodes the modified menu array back to JSON format._

_I hope this helps! Let me know if you have any questions._

Rate this post

3 of 5 based on 5667 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us