如何使用php& amp;创建带子菜单的动态菜单MySQL的

时间:2012-09-02 21:48:39

标签: php mysql

我希望有一个动态菜单,使用php和mysql从表中提供。

我的表格如下:

sec_id  sec_name    sec_group
1   section 1   group 1
2   section 2   group 1
3   section 3   group 2
4   section 4   group 1
5   section 5   group 3

我可以进行查询以获取并显示唯一的sec_group值,但无法找到将sec_name包含到每个sec_group中的方法

//Query by unique sec_group
$qry_secs="SELECT DISTINCT sec_group FROM tbl_user_sec ORDER BY sec_id ASC";
$result_secs = mysql_query($qry_secs);

//echo values
while($row_secs = mysql_fetch_assoc($result_secs)){
 echo '<ul><li><a href="#">'.$row_secs['sec_group'].'</a></li></ul>';
}

最终,HTML应该像下面的代码一样。

<ul>
<li><a href="#">Group 1</a>
  <ul>
  <li><a href="#">Section 1</a></li>
  <li><a href="#">Section 2</a></li>
  <li><a href="#">Section 4</a></li>
  </ul>
</li>

<li><a href="#">Group 2</a>
  <ul>
  <li><a href="#">Section 3</a></li>
  </ul>
</li>

<li><a href="#">Group 3</a>
  <ul>
  <li><a href="#">Section 5</a></li>
  </ul>
</li>
</ul>

任何想法?

2 个答案:

答案 0 :(得分:3)

$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>";

如果您不关心按sec_id

排序结果,则有another solution

答案 1 :(得分:0)

$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';