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? Quote Link to comment 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... Quote Link to comment 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 Quote Link to comment 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!"; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.