[英]Recursive tree builder from depth
I am trying to build a nested array (menu) by using the depths in the flat tree that was given back to me from MySQL. 我正在尝试通过使用从MySQL返回给我的平面树中的深度来构建嵌套数组(菜单)。
Unfortunately I have been struggeling for days with this code and I cannot seem to get it working properly. 不幸的是,我一直在努力使用这段代码,而且似乎无法正常工作。 Is there anyone who could help me out and tell me how to do it properly?
是否有人可以帮助我并告诉我如何正确进行操作?
$dataset = json_decode('{"results":[{"title":"Hoofdcategorie","clean_title":"hoofdcategorie","depth":0},{"title":"Hoofdcategorie 2","clean_title":"hoofdcategorie 2","depth":0},{"title":"Subcategorie","clean_title":"subcategorie","depth":1}]}');
function buildTree(&$tree, $current_depth = 0) {
$formattedTree = [];
// start at zero and loop through
while($node = current($tree)) {
// if our node depth is bigger then our current depth
if($node->depth > $current_depth) {
// repeat function from current depth
$formattedTree[] = buildTree($tree, $node->depth);
} elseif($node->depth < $current_depth) {
// we need to go one stap backwards, return the tree
return $formattedTree;
} else {
// add current iteration
$formattedTree[] = $node;
// proceed to next iteration
next($tree);
}
}
echo '<pre>';
print_r( $formattedTree );
echo '</pre>';
}
buildTree($dataset->results, 0);
It just simply won't build the tree correctly. 只是根本无法正确构建树。
Best regards 最好的祝福
Check here for managing hierarchical data http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ 在此处检查用于管理分层数据http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
You can also look here for implementing nested set https://github.com/ben-nsng/nestedset-php 您也可以在这里查看实现嵌套集https://github.com/ben-nsng/nestedset-php
Now guide yourself to implement it. 现在指导自己实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.