I’m trying to create an dynamic menu from mysql table with php but i don’t know how to create the non category menu, here is what i have so far and is working only the categories with submenus but the non categories ones they are not shown on echo.
MySQL category menu Table:
catid name group 1 category name 1 0 -> whithout submenu 2 category name 2 1 -> category 3 category name 3 1 -> category 4 category name 4 0 -> whithout submenu 5 category name 5 0 -> whithout submenu
MySQL sub menus Table:
id name parentid -> catid (category menu table) 1 name 1 2 2 name 2 3 3 name 3 3 4 name 4 3 5 name 5 2
My Php code:
<?php function loop($array = array(), $parentID = 0) { if (!empty($array[$parentID])) { echo '<ul>'; foreach ($array[$parentID] as $items) { echo '<li>'; echo $items['name']; loop($array, $items['catid']); echo '</li>'; } echo '</ul>'; } } function menu() { $query = $db->query("SELECT m.name, m.parentid, c.group FROM `submenus` m LEFT JOIN( SELECT catid, group, parentid, ico, STATUS , MIN(name) AS category FROM `menu_categories` GROUP BY catid ) c ON m.parentid = c.catid"); $array = array(); if ($db->numRows($query)) { while ($rows = $db->fetch($query)) { $array[$rows['parentid']][] = $rows; } loop($array); } } echo menu(); ?>
Advertisement
Answer
Instead of a Left Join
, wich leaves out the unpaired records in your category table, try a Full Join
<?php function loop($array = array(), $parentID = 0) { if (!empty($array[$parentID])) { echo '<ul>'; foreach ($array[$parentID] as $items) { echo '<li>'; echo $items['name']; loop($array, $items['catid']); echo '</li>'; } echo '</ul>'; } } function menu() { $query = $db->query("SELECT m.name, m.parentid, c.group FROM `submenus` m FULL JOIN( SELECT catid, group, parentid, ico, STATUS , MIN(name) AS category FROM `menu_categories` GROUP BY catid ) c ON m.parentid = c.catid"); $array = array(); if ($db->numRows($query)) { while ($rows = $db->fetch($query)) { $array[$rows['parentid']][] = $rows; } loop($array); } } echo menu(); ?>