我有存储在数组中的数据集上的foreach循环父和子节点进行排序通过在PHP与父子IDS引用本身: id
,parent_id
,title
等顶层有parent_id
的0
,并且可以有无数的父子关系。递归函数来使用阵列
因此,我正在用递归函数中的foreach
循环对这个数组进行排序,以检查每个数组元素与它的父元素,并且我认为我一直盯着这个方法太长了。
我确实以正确的顺序结束了元素,但我似乎无法让我的列表正确嵌套,这让我觉得这个方法并不真正起作用。
- 这是最好的路线?
- 我能做些什么来改善和修复这种方法
- 我还可以申请另一个技巧吗?
这里是我的源:
<div>
<div>Subpages</div>
<ul>
<?php subPages($this->subpages->toArray(), 0) ?>
</ul>
<br>
<a href="javascript:;" onclick="">Add New Subpage</a>
</div>
<?php
function subPages($subpages, $parent){
foreach($subpages as $key => &$page){
$newParent = $page['id'];
//If the current page is the parrent start a new list
if($page['id'] == $parent)
{
//Echo out a new list
echo '<ul>';
echo '<li class="collapsed">';
echo '<a href="javascript:;" class="toggle">+</a>';
echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';
subPages($subpages, $newParent);
echo '</li>';
echo '</ul>';
}
//If the page's parent id matches the parent provided
else if($page['parent_id'] == $parent)
{
//Echo out the link
echo '<li class="collapsed">';
echo '<a href="javascript:;" class="toggle">+</a>';
echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';
//Set the page as the new parent
$newParent = $page['id'];
//Remove page from array
unset($subpages[$key]);
//Check the rest of the array for children
subPages($subpages, $newParent);
echo '</li>';
}
}
}
?>
与往常一样,任何援助表示赞赏。请让我知道,如果有什么不明确的。
听起来好像你正在描述一棵树的[深度优先搜索](http://en.wikipedia.org/wiki/Depth-first_search)。或者['heapsort'](http://en.wikipedia.org/wiki/Heapsort)。 – Matt 2012-08-16 15:28:04
重构树或使用队列处理迭代,并且只有在队列中已经存在或处理完毕的列表中才添加到队列中。 – Waygood 2012-08-16 15:31:17
所以没有优雅的方式来遍历和吐出数据? – dbergunder 2012-08-16 20:54:37