I am attempting to create a simple unordered list menu using PHP. The list is populated from MySQL. I am having a lot of trouble finding instructions that match my specific needs.
Requirements
- I am trying to avoid self-referencing functions.
- I am trying to do this with one query for performance efficiency.
- I am using a modified preordered tree traversal algorithm for displaying the menu.
- Each row must be surrounded by a list item tag.
- Lists must be opened and closed where nodes begin and end
Code:
CREATE TABLE IF NOT EXISTS `maj_topmenu` (
`menu_id` int(11) NOT NULL auto_increment,
`menu_title` varchar(100) NOT NULL default '',
`menu_url` varchar(200) NOT NULL default '',
`menu_level` int(10) NOT NULL default '0',
`parent_id` int(11) NOT NULL default '0',
`lft` int(10) NOT NULL,
`rgt` int(10) NOT NULL,
`displayorder` int(11) default NULL,
PRIMARY KEY (`menu_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
INSERT INTO `maj_topmenu` (`menu_id`, `menu_title`, `menu_url`, `menu_level`, `parent_id`, `lft`, `rgt`, `displayorder`) VALUES
(1, 'Home', '/home', 0, 0, 1, 2, 0),
(2, 'About Us', '/about', 0, 0, 5, 10, 10),
(3, 'News', '/news', 0, 0, 3, 4, 5),
(4, 'Blogs', '/viewblog', 0, 0, 11, 12, 15),
(5, 'Contact Us', '/contact', 0, 0, 13, 14, 20),
(6, 'Sub Menu 1', '/link1', 1, 2, 6, 9, 0),
(7, 'Sub Menu 2', '/link2', 2, 6, 7, 8, 0);
PHP Part
$topmenu = '';
$nodes=array();
$nlbr = "
";
// Now, retrieve all descendants of the $root node
$sql="SELECT n.menu_title, n.menu_title, n.menu_url, n.parent_id, n.lft, n.rgt FROM maj_topmenu AS n, maj_topmenu AS p WHERE n.lft BETWEEN p.lft AND p.rgt AND p.parent_id = '0' ORDER BY n.lft";
$result = mysql_query($sql) or die(mysql_error());
$topmenu .= '<ul>' . $nlbr;
while ($row = mysql_fetch_array($result))
{
if ( ($row['rgt'] - $row['lft']) == 1 )
{
// No child elements
if (sizeof($nodes) == 0)
{
// We're at the top with no children
$topmenu .= '<li>'.$row['lft'].' <a href="'.$row['menu_url'].'">'.$row['menu_title'].'</a> '.$row['rgt'].'</li>' . $nlbr;
continue;
}
else
{
// We're in the middle with no children; We'll need to end at least one branch
$topmenu .= '<li>'.$row['lft'].' <a href="'.$row['menu_url'].'">'.$row['menu_title'].'</a> '.$row['rgt'].'</li>' . $nlbr;
while ( ($row['rgt'] + 1) - end($nodes) == 0 )
{
$topmenu .= '</ul>' . $nlbr;
array_pop($nodes);
}
continue;
}
}
else
{
// Start a new branch
$topmenu .= '<li>'.$row['lft'].' <a href="'.$row['menu_url'].'">'.$row['menu_title'].'</a> '.$row['rgt'].'</li>' . $nlbr;
$topmenu .= '<ul>' . $nlbr;
// End leaf at this point later
$nodes[] = $row['rgt'];
}
}
$topmenu .= '</ul>';
The issue I am having is that the loop doesn't end the nodes in the proper places. If I'm on a 3rd level branch, it may end either too many or too few lists.
This script may be used later for extensive hierarchy data which is why I went with the MPTTA for this and I'm trying to avoid having to do queries at numerous levels.