简体   繁体   中英

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.

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/

You can also look here for implementing nested set https://github.com/ben-nsng/nestedset-php

Now guide yourself to implement it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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