【问题标题】:Laravel etrepat/baum How to show whole treeLaravel etrepat/baum 如何显示整棵树
【发布时间】:2015-10-20 21:26:38
【问题描述】:
如何显示整棵树。我有一个 3 级导航(首先是根)。使用该代码,我只会看到第二层。
$tree = \App\Category::where('identifier', 'soccer')->first();
foreach($tree->getDescendants()->toHierarchy() as $descendant) {
echo "{$descendant->name} <br>";
}
【问题讨论】:
标签:
php
laravel
navigation
eloquent
【解决方案1】:
您可以通过以下方式获取包括根在内的整个树:
$root = Table::where('id', '=', $id)->first();
$tree = $root->getDescendantsAndSelf()->toHierarchy();
现在 $tree 是树形结构,您需要递归或使用队列数据结构(DFS 或 BFS)遍历它。树上的每个项目都会有一个 children 属性及其子项
一些伪遍历将是:
function traverseBFS(tree) {
q = Queue()
q.push(tree[0]);
while (!q.empty()) {
item = q.top(); q.pop();
// do what you need with item
foreach (item->children as child) {
q.push(child);
}
}
}