I have an array like this:
Array
(
[0] => stdClass Object
(
[ID] => 1
[menu_item_parent] => 0
[title] => Home
[url] => http://www.example.com/
)
[1] => stdClass Object
(
[ID] => 2
[menu_item_parent] => 0
[title] => Menu 2
[url] => http://www.example.com/menu-2/
)
[2] => stdClass Object
(
[ID] => 3
[menu_item_parent] => 2
[title] => Sub Menu 1
[url] => http://www.example.com/menu-2/sub-menu-1
[target] =>
)
[3] => stdClass Object
(
[ID] => 4
[menu_item_parent] => 0
[title] => Menu 4
[url] => http://www.example.com/menu-4/
[target] =>
)
)
Now you can see 3rd item of an array is child item of the second array item(see the column menu_item_parent
).Now my question is how can i show this parent item with it’s child item using this array.Please help.
Finally solve my problem with the help of @Matt.C given link.Thanks to @Matt.C. Here’s the solution:
Firstly get the menu items as a flat array:
Then iterate over the array of the menu items:
Write the first parent item
<li>:
Check that this items’ parent id matches the stored parent id:
If the next item does not have the same parent id and we have a sub-menu declared then close the sub-menu
<ul>
Again, if the next item in the array does not have the same parent id close the
<li>
Try this : I added the input as array, change to objects as per your question.
Output:
Here’s a very simple class for your WordPress-specific problem with a
get_submenu
function that returns all submenu items:Usage. Construct an instance:
Iterate:
And obtain the submenu inside the loop:
Before displaying the submenu, you can check if it exists:
You can iterate over the array and if the object has a parent add it to a
children
array of that parent. For example:Will convert:
To:
Then you can iterate over each object and show its children if needed:
Check using foreach function in php.
like
Output:
This would be my solution. Moves the childs under the parent object into
children
and creates a boolean under the parent calledhas_child
which value will be1
. Finally, unsets and removes the child from the main variable.