Mister PHP
Mister PHP

Reputation: 327

How to build a tree in php having id, parent_id and depth variables

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

Upvotes: 0

Views: 3498

Answers (1)

AjayR
AjayR

Reputation: 4179

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

Upvotes: 4

Related Questions