How to build a tree in php having id, parent_id an

2019-02-20 20:35发布

问题:

From the mysql query i have id, parent_id and depth variables

depth starts from 0

can you give me an elegant solution or a good link

I am using CI

回答1:

First you have to write a recursive function to read all the child elements and output them as "" and <"li>".

Once you get the proper shape. you can use the following example code to turn li to tree.

http://www.dynamicdrive.com/dynamicindex1/navigate1.htm

or

http://odyniec.net/articles/turning-lists-into-trees/

You can like below code also

   function print_list($array, $parent=0) {
        print "<ul>";
        foreach ($array as $row) {
            if ($row->parent_id == $parent) {
                print "<li>$row->title";
                print_list($array, $row->id);  # recurse
                print "</li>";
        }   }
        print "</ul>";
    }

print_list is a recursive function and $array is all the rows from database.

PHP / MySQL build tree menu