I’m trying to generate a tree structure from a table in a database. The table is stored flat, with each record either having a parent_id or 0. The ultimate goal is to have a select box generated, and an array of nodes.
The code I have so far is :
function init($table, $parent_id = 0) { $sql = 'SELECT id, {$this->parent_id_field}, {$this->name_field} FROM $table WHERE {$this->parent_id_field}=$parent_id ORDER BY display_order'; $result = mysql_query($sql); $this->get_tree($result, 0); print_r($this->nodes); print_r($this->select); exit; } function get_tree($query, $depth = 0, $parent_obj = null) { while($row = mysql_fetch_object($query)) { /* Get node */ $this->nodes[$row->parent_category_id][$row->id] = $row; /* Get select item */ $text = ''; if($row->parent_category_id != 0) { $text .= ' '; } $text .= '$row->name'; $this->select[$row->id] = $text; echo '$depth $text\n'; $sql = 'SELECT id, parent_category_id, name FROM product_categories WHERE parent_category_id='.$row->id.' ORDER BY display_order'; $nextQuery = mysql_query($sql); $rows = mysql_num_rows($nextQuery); if($rows > 0) { $this->get_tree($nextQuery, ++$depth, $row); } } }
It’s almost working, but not quite. Can anybody help me finish it off?
I think it’s this line here:
should be:
You are only indenting it once, not the number of times it should be indented.
And this line:
should be:
Note that you should probably follow the advice in the other answer though, and grab the entire table at once, and then process it at once, because in general you want to minimize round-trips to the database (there are a few use cases where the way you are doing it is more optimal, such as if you have a very large tree, and are selecting a small portion of it, but I doubt that is the case here)