php 如何使用php和mysql创建带有子菜单的动态菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12239995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:07:46  来源:igfitidea点击:

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

phpmysql

提问by Azukah

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

我想要一个动态菜单,使用 php 和 mysql 从表中提供。

My table looks like this:

我的桌子看起来像这样:

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

I can do a query to get and display unique sec_group values but can't figure out a way to include sec_name into each sec_group

我可以执行查询以获取和显示唯一的 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>';
}

Eventually, the HTML should like the code below.

最终,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>

any ideas?

有任何想法吗?

回答by Peter

$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 solutionif you don't care about sorting result by sec_id

如果您不关心排序结果,还有另一种解决方案sec_id

回答by hjpotter92

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