簡體   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