douyi1779 2018-06-18 17:32
浏览 123

从深度的递归树建设者

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.

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

  • 写回答

1条回答 默认 最新

  • doushouj966020 2018-06-18 18:12
    关注

    Check here for managing hierarchical data 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

    Now guide yourself to implement it.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型