Array
(
[0] => WP_Post Object
(
[ID] => 35
[menu_item_parent] => 0
)
[1] => WP_Post Object
(
[ID] => 38
[menu_item_parent] => 35
)
[2] => WP_Post Object
(
[ID] => 36
[menu_item_parent] => 35
)
[3] => WP_Post Object
(
[ID] => 37
[menu_item_parent] => 0
)
)
<?php
$items = [
['ID'=>35, 'menu_item_parent'=>0],
['ID'=>38, 'menu_item_parent'=>35],
['ID'=>36, 'menu_item_parent'=>35],
['ID'=>39, 'menu_item_parent'=>36],
['ID'=>40, 'menu_item_parent'=>39],
['ID'=>41, 'menu_item_parent'=>39],
['ID'=>37, 'menu_item_parent'=>0],
];
function find_childrens($items, $parentItem) {
$ret = [];
foreach($items as $item) {
if ($item['menu_item_parent'] == $parentItem['ID']) {
$treeItem = $item;
$treeItem['subitems'] = find_childrens($items, $item);
$ret[] = $treeItem;
}
}
return $ret;
}
$tree = [];
foreach($items as $item) {
if ($item['menu_item_parent'] == 0) {
$treeItem = $item;
$treeItem['subitems'] = find_childrens($items, $item);
$tree[] = $treeItem;
}
}
echo '<pre>';
print_r($tree);
echo '</pre>';
echo '<hr>';
function printer($treeItem, $level) {
if ($level) echo str_repeat('--', $level);
echo $treeItem['ID'].'<br>';
if ($treeItem['subitems']) {
foreach($treeItem['subitems'] as $subItem) {
printer($subItem, $level+1);
}
}
}
foreach($tree as $treeItem) printer($treeItem, 0);
Array
(
[0] => Array
(
[ID] => 35
[menu_item_parent] => 0
[subitems] => Array
(
[0] => Array
(
[ID] => 38
[menu_item_parent] => 35
[subitems] => Array
(
)
)
[1] => Array
(
[ID] => 36
[menu_item_parent] => 35
[subitems] => Array
(
[0] => Array
(
[ID] => 39
[menu_item_parent] => 36
[subitems] => Array
(
[0] => Array
(
[ID] => 40
[menu_item_parent] => 39
[subitems] => Array
(
)
)
[1] => Array
(
[ID] => 41
[menu_item_parent] => 39
[subitems] => Array
(
)
)
)
)
)
)
)
)
[1] => Array
(
[ID] => 37
[menu_item_parent] => 0
[subitems] => Array
(
)
)
)
====================================================
35
-- 38
-- 36
---- 39
------ 40
------ 41
37