2

我想要一个使用 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>

有任何想法吗?

4

2 回答 2

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

于 2012-09-02T22:05:44.583 回答
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';
于 2012-09-02T22:00:58.673 回答