/ Published in: PHP
This code is meant to take it easy on the database by only requiring one query. It also prints nicely indented html and can be used in pretty much any situation where you have a flat parent/child structure that needs to be converted into a tree. This method can also build the tree in a single pass in some cases. Note - I have also added code to have it ignore orphaned children.
Expand |
Embed | Plain Text
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>PHP Tree Builder</title> </head> <body> <?php function tree_example(){ $id_column = "tag_id"; //The column that contains the id of each node $parent_column = "parent_id"; //The column that contains the id of each node's parent $text_column = "name"; //The column to display when printing the tree to html //a sample array - normally you would create this array from your database table (sorted by id) //it is important that they keys of the array = the id of each row $rows[6] = array("tag_id" => 6, "name" => "dessert", "parent_id" => NULL); //a parent defined after the child $rows[9] = array("tag_id" => 9, "name" => "donut", "parent_id" => 6); //a parent defined after another late parent and with two children //build the tree - this will complete in a single pass if no parents are defined after children foreach($rows as $row_id => $row){ if($row[$parent_column]){ if((!array_key_exists($row[$parent_column], $rows)) and (!array_key_exists($row[$parent_column], $tree_index))){ } else{ $parent = & $tree_index[$row[$parent_column]]; $tree_index[$row_id] = & $parent['children'][$row_id]; } } } else{ $tree_index[$row_id] = & $tree[$row_id]; } } } //we are done with index now so free it //start printing out the tree $html = " <div id='tree'>\n"; $html .= " <ul>\n"; foreach($tree as $node){ //go to each top level node and print it and it's children $html .= print_tree($node, $text_column, 8, 2); } $html .= " </ul>\n"; $html .= " </div>\n"; return $html; } //recursive function used to print tree structure to html function print_tree($node, $text_column, $indent, $indent_size){ //print the current node if($node['children']){ //then print it's children nodes foreach($node['children'] as $child){ $html .= print_tree($child, $text_column, $indent + $indent_size * 2, $indent_size); } } $html .= "</li>\n"; return $html; } ?> </body> </html>
Comments
Subscribe to comments
You need to login to post a comment.

great one! I've been trying to figure it out the whole day..
Hi this is the great example, But what should be the Sql query if you want to output the tree of a desired user in the Database?
I have it returning a Fatal Error on line 37. I get the array from a database but parentid are NOT NULL. Instead, root elements have parentid = 0. So I have changed line 31 to
if((int)($row[$parentcolumn])>0){but it still has an error somewhere onif(arraykeyexists($row[$parentcolumn], $tree_index)){. Any thoughts? Thanks.