从深度的递归树建设者

时间:2018-06-18 17:32:24

标签: php recursion tree

我正在尝试使用从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);

它只是不能正确构建树。

祝你好运

1 个答案:

答案 0 :(得分:0)

点击此处查看管理层次结构数据http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

您还可以在此处查看实现嵌套集 https://github.com/ben-nsng/nestedset-php

现在指导自己实施它。