> Dear list, > I have been facing problems while building dynamic menu. I am using > database to store the Menu items. I am having two fields in the database > table called ParentID, ChildID. > Parent Child > 1 0 > 2 0 > 3 0 > 4 1 > 5 1 > 6 1 > 7 3 > 8 3 > 9 4 > 10 8 > I want to build menu from this. Please suggest me the way to do so. > > Thanks in Advance
The following will build a two-level menu as an unordered list, with the second level appearing if its parent is selected. The variable "$gpid" is grandparent id for a third level, which is not displayed in this menu. Some checks are done in order to display a menu item differently if it is the current page or an ancestor of the current page. (In the design I took this example from, third level menus are shown in a different place.) // build menu array $menu_sql = "SELECT id, parentid, menuname, FROM pages"; $menu_result = mysql_query($menu_sql); if (mysql_num_rows($menu_result) > 0) { while ($menu_row = mysql_fetch_array($menu_result)) { $menu_array[] = array($menu_row["id"], $menu_row["parentid"], $menu_row["menuname"]); } } // home id is 10 $id = isset($_GET["id"]) ? $_GET["id"] : 10; $pid = isset($_GET["pid"]) ? $_GET["pid"] : 0; $gpid = isset($_GET["gpid"]) ? $_GET["gpid"] : ""; // display menu echo("<ul>"); foreach ($menu_array as $menu) { // if the parent id is 0, menu item is main level if ($menu[1] == "0") { if ($menu[0] == $id || $menu[0] == $pid || $menu[0] == $gpid) { echo("<li><a class=\"selected\" href=\"" . $PHP_SELF . "?id=" . $menu[0] . "&pid=0\">" . $menu[2] . "</a>"); foreach ($menu_array as $menu2) { if ($menu2[1] == $menu[0]) { $subcount[] = $menu2[1]; } } if (count($subcount) > 0) { echo("<ul>"); foreach ($menu_array as $menu3) { if ($menu3[1] == $menu[0]) { if ($menu3[0] == $id || $menu3[0] == $pid) { echo("<li><a class=\"selected\" href=\"" . $PHP_SELF . "?id=" . $menu3[0] . "&pid=" . $menu3[1] . "\">" . $menu3[2] . "</a></li>"); } else { echo("<li><a href=\"" . $PHP_SELF . "?id=" . $menu3[0] . "&pid=" . $menu3[1] . "\">" . $menu3[2] . "</a></li>"); } } } echo("</ul>"); } echo("</li>"); } else { echo("<li><a href=\"" . $PHP_SELF . "?id=" . $menu[0] . "&pid=0\">" . $menu[2] . "</a></li>"); } } } echo("</ul>\n"); HTH -- Lowell Allen -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php