nested UL tree from hierarchical db
| From: | Justin French | Date: | Wed, 10 Mar 2004 09:09:02 +0000 |
| Subject: | nested UL tree from hierarchical db | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-179990@lists.php.net to get a copy of this message | ||
Hi all,
I'm playing around with "Modified Preorder Tree Traversal" as discussed in an article on sitepoint <http://www.sitepoint.com/article/hierarchical-data-database/>, which includes this function:
<?php
function display_tree($root) {
// retrieve the left and right value of the $root node
$result = mysql_query('SELECT lft, rgt FROM tree '.
'WHERE title="'.$root.'";');
$row = mysql_fetch_array($result);
// start with an empty $right stack $right = array();
// now, retrieve all descendants of the $root node
$result = mysql_query('SELECT title, lft, rgt FROM tree '.
'WHERE lft BETWEEN '.$row['lft'].' AND '.
$row['rgt'].' ORDER BY lft ASC;');
// display each row
while ($row = mysql_fetch_array($result)) {
// only check stack if there is one
if (count($right)>0) {
// check if we should remove a node from the stack
while ($right[count($right)-1]<$row['rgt']) {
array_pop($right);
}
}
// display indented node title
echo str_repeat(' ',count($right)).$row['title']."\n";
// add this node to the stack $right[] = $row['rgt']; }} ?> This is outputting a text-based tree of the data in the database, but what I'd like to do is modify it to output a series of nested ul's (unordered lists) to describe the nesting, rather than relying on spaces and newlines. I've had a couple of attempts, with no luck... can someone shed some light on how this might be achieved? --- Justin French http://indent.com.au