etrader Posted October 30, 2011 Share Posted October 30, 2011 I have a mysql table with the structure of ID Menu_Name Parent_ID 1 Finance NULL 2 Business NULL 3 Investment 1 4 Trading 2 How can I create a html <ul><li> list based on the parent? Link to comment https://forums.phpfreaks.com/topic/250080-how-to-create-a-menu-list-from-mysql-data/ Share on other sites More sharing options...
joel24 Posted October 30, 2011 Share Posted October 30, 2011 use a multi-dimensional array... i.e. $menu[1]['name']='Finance'; $menu[1][x]='Item'; $sql=@mysql_query("SELECT * FROM tableName ORDER BY IFNULL(parent_id,0)"); $menu=array(); while ($row=mysql_fetch_assoc($sql)) { if (is_null($row['parent_id'])) { $menu[$row['id']]['name']=$row['menu_name']; } else { $menu[$row['parent_id'][]=$row['menu_name']; } foreach ($menu AS $m) { echo "<ul><li>{$m['name']}"; if (is_array($m) { echo "<ul>"; foreach ($m AS $m2) { echo "<li>$m2</li>"; } echo "</ul>"; } echo "</li></ul>"; } html may be wrong but you get the idea... Link to comment https://forums.phpfreaks.com/topic/250080-how-to-create-a-menu-list-from-mysql-data/#findComment-1283372 Share on other sites More sharing options...
etrader Posted October 30, 2011 Author Share Posted October 30, 2011 Thanks a million! It did lead me on the right direction. P.S. The wonderful quotation in your signature made my day I wish the best for your Roboroster project Link to comment https://forums.phpfreaks.com/topic/250080-how-to-create-a-menu-list-from-mysql-data/#findComment-1283381 Share on other sites More sharing options...
MasterACE14 Posted October 30, 2011 Share Posted October 30, 2011 Just 1 improvement to what joel24 posted. Rather than suppressing a potential error, check whether there is records or not. $sql=mysql_query("SELECT * FROM tableName ORDER BY IFNULL(parent_id,0)"); if(mysql_num_rows($sql) > 0) { $menu=array(); while ($row=mysql_fetch_assoc($sql)) { if (is_null($row['parent_id'])) { $menu[$row['id']]['name']=$row['menu_name']; } else { $menu[$row['parent_id'][]=$row['menu_name']; } foreach ($menu AS $m) { echo "<ul><li>{$m['name']}"; if (is_array($m) { echo "<ul>"; foreach ($m AS $m2) { echo "<li>$m2</li>"; } echo "</ul>"; } echo "</li></ul>"; } } else { echo "There is no records!"; } Link to comment https://forums.phpfreaks.com/topic/250080-how-to-create-a-menu-list-from-mysql-data/#findComment-1283384 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.