Page 1 of 1

Tree Display

Posted: Mon Oct 20, 2008 12:50 pm
by raj_2006
Hi All,

I am trying to display a tree using php and mysql using the below code

Table structure and data

CREATE TABLE IF NOT EXISTS `tb_tree` (
`tid` int(9) NOT NULL auto_increment,
`parent` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`lft` int(5) NOT NULL,
`rgt` int(5) NOT NULL,
PRIMARY KEY (`tid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;


INSERT INTO `tb_tree` (`tid`, `parent`, `title`, `lft`, `rgt`) VALUES
(1, '', 'Food', 1, 18),
(2, 'Food', 'Fruit', 2, 11),
(3, 'Fruit', 'Red', 3, 6),
(4, 'Red', 'Cherry', 4, 5),
(5, 'Fruit', 'Yellow', 7, 10),
(6, 'Yellow', 'Banana', 8, 9),
(7, 'Food', 'Meat', 12, 17),
(8, 'Meat', 'Beaf', 13, 14),
(9, 'Meat', 'Pork', 15, 16);

Code: Select all

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']; 
   } 
} 
 
 
display_tree('food');
But instead of indentation it is displaying as

Food Fruit Red Cherry Yellow Banana Meat Beaf Pork

The order is correct but it is not showing as a tree.I have tried a lot but cannot find out a single hint.Could you please tell me how can I make it a tree display.

Thanks for your co-operation in advance.

Regards,
Raj

Re: Tree Display

Posted: Mon Oct 20, 2008 1:03 pm
by onion2k
Image

Hehe.

Seriously though, where you echo each item you need to use a non-breaking space (eg "&nbsp;") rather than a real space, and "<br />" rather than \n. Alternatively use a preformat tag (eg "<pre></pre>") around your text, or the CSS equivalent.