我有一个 SQL 连接,它输出一个对象数组,它是这样排序的
(
[0] => listItem Object
(
[name] => TV
[parentId] => 0
[id] => 1
[childs] => Array
(
[0] => listItem Object
(
[name] => mini tv
[parentId] => 1
[id] => 29
[childs] => Array
(
[0] => listItem Object
(
[name] => tiny TV
[parentId] => 29
[id] => 548
)
)
)
)
)
[1] => listItem Object
(
[name] => RADIO
[parentId] => 0
[id] => 2
[childs] => Array
(
[0] => listItem Object
(
[name] => mini radio
[parentId] => 2
[id] => 30
)
[1] => listItem Object
(
[name] => Tiny LCD
[parentId] => 2
[id] => 551
)
)
)
[2] => listItem Object
(
[name] => Stereo
[parentId] => 0
[id] => 550
)
[3] => listItem Object
(
[name] => Joe the Plumber
[parentId] => 0
[id] => 568
[childs] => Array
(
[0] => listItem Object
(
[name] => Joe the Plumber
[parentId] => 568
[id] => 569
[childs] => Array
(
[0] => listItem Object
(
[name] => Joe the Plumber
[parentId] => 569
[id] => 570
[childs] => Array
(
[0] => listItem Object
(
[name] => Joe the Plumber
[parentId] => 570
[id] => 571
)
)
)
)
)
)
)
)
我以这种方式对其进行排序,因为我想将其输出为具有适当层次结构的 a 。
我有这个功能
function buildHTML($tree){
echo 'building tree';
foreach($tree as $item){
$topItem = makeHtmlListItem($item);
$pos = strpos($topItem, '</li>');
$newItem = substr($topItem,0 , $pos);
echo $newItem;
foreach($item->childs as $subItem){
echo '<ul>' . makeHtmlListItem($subItem) . '</ul>' ;
}
echo '</li>';
}
}
但它只达到了第二个层次。如何以任意深度到达底部?我设法通过递归来做到这一点,但现在我想在没有递归的情况下做到这一点,我快疯了。