繁体   English   中英

深度递归树生成器

[英]Recursive tree builder from depth

我正在尝试通过使用从MySQL返回给我的平面树中的深度来构建嵌套数组(菜单)。

不幸的是,我一直在努力使用这段代码,而且似乎无法正常工作。 是否有人可以帮助我并告诉我如何正确进行操作?

$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);

只是根本无法正确构建树。

最好的祝福

在此处检查用于管理分层数据http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

您也可以在这里查看实现嵌套集https://github.com/ben-nsng/nestedset-php

现在指导自己实施。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM