how to create dynamic menu with sub-menu with php & mysql

后端 未结 2 1701
慢半拍i
慢半拍i 2021-01-07 05:37

I want to have a dynamic menu that feeds from a table using php and mysql.

My table looks like this:

sec_id  sec_name    sec_group
1   section 1   g         


        
相关标签:
2条回答
  • 2021-01-07 05:52
    $q = mysql_query("SELECT sec_id, sec_name, sec_group FROM tbl_user_sec ORDER BY sec_id");
    
    // prepare data 
    $groups = Array();
    while($w = mysql_fetch_assoc($q)) {
      if(!isset($groups[$w['sec_group']])) $groups[$w['sec_group']] = Array();
      $groups[$w['sec_group']][] = $w;
    }
    
    // display data
    echo "<ul>";
    foreach($groups as $group_name => $sections) {
      echo '<li><a href="#">'.$group_name.'</a><ul>';
      foreach($sections as $section) {
        echo '<li><a href="#">'.$section['sec_name'].'</a>';
      }
      echo '</ul></li>';
    }
    echo "</ul>";
    

    There is another solution if you don't care about sorting result by sec_id

    0 讨论(0)
  • 2021-01-07 05:59
    $qry_secs="SELECT DISTINCT sec_group FROM tbl_user_sec ORDER BY sec_id ASC";
    $result_secs = mysql_query($qry_secs);
    echo '<ul>\n';
    //echo values
    while($row_secs = mysql_fetch_assoc($result_secs)) {
        echo '<li><a href="#">'.$row_secs['sec_group'].'</a></li>\n';
        echo '<ul>\n';
        $newqry = "SELECT sec_name FROM tbl_user_sec WHERE `sec_group` = '" . mysql_real_escape_string($row_secs['sec_group'] . "'";
        $result = mysql_query($newqry);
        while($row = mysql_fetch_assoc($result) ) {
            echo '<li><a href="#">' . $row['sec_name'] . '</li>\n';
        echo '</ul>\n';
    }
    echo '</ul>\n';
    
    0 讨论(0)
提交回复
热议问题