问题描述
我在mysql中设置了一个表,如下:
I have a table set up in mysql as follows:
我想创建一个侧边栏类别导航,其中包含父类别 - 子类别 - 以及我存储在另一个表中的可能的第三级类别.
I would like to create a sidebar category navigation with Parent category - subcategories - and possible third level categories which I have stored in another table.
我试图让它们显示在这样的树结构中:
I am trying to get them to display in a tree structure like so:
一夜情
- 俱乐部和社团
- 公共房屋
- 餐厅
- 出租车和私人租用车辆
- 剧院和音乐厅
- 酒吧
住宿
- 民宿
- 旅馆
- 度假住宿
- 酒店
- 自助式住宿
农业
- 农业机械及备件
- 农商行
- 动物饲料
- 乡村服饰
- 乳制品
等
目前我可以创建以下内容:
At the moment I am able to create the following:
使用此代码:
$dbc = mysql_connect($db_host,$db_user,$db_pass);
$sdb = mysql_select_db($db_database);
$query = 'SELECT category_name, subcategory_name FROM categories, subcategories WHERE subcategory_parent = category_name';
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$catname = $row["category_name"];
$subcatname = $row["subcategory_name"];
echo "<li>$catname</li><ul><li>$subcatname</li></ul>";
}
我想让第一级类别只显示一次,子类别在它们下面的列表中.谁能告诉我最有效的方法吗?我想我需要使用 foreach 但不确定.
I want to get the first level category to display only once with the subcategories in a list below them. Can anyone tell me the most efficient way to do this? I think I need to use foreach but am not sure.
我建立的第三级类别表和这个表结构一样,但是是subsubcategory_id/subsubcategory_parent/subsubcategory_name.
The third level category table I have set up has the same structure as this table but is subsubcategory_id / subsubcategory_parent / subsubcategory_name.
推荐答案
只在catname
变化时输出.您还需要先按 category_name 对查询进行排序.
only output the catname
when it changes. You will also need to order your query by category_name first.
$row = mysql_fetch_array($result);
$catname = $row["category_name"];
$subcatname = $row["subcategory_name"];
$last = $catname;
echo "<li>$catname</li><ul>"
while($row = mysql_fetch_array($result)) {
$catname = $row["category_name"];
$subcatname = $row["subcategory_name"];
if($last != $catname){
echo "</ul><li>$catname</li><ul>"
}
echo "<li>$subcatname</li>";
$last = $catname;
}
echo "</ul>";
只需重新完整阅读问题并想说,当涉及到分层树时,使用父/子(或类别/子/子子)不是最好的方法.虽然它确实有效,但它通常需要多个查询和递归函数才能显示.更好的方法是使用专门为此目的而制作的 嵌套集.
Just re-read the question fully and want to say that when it comes to hierarchical trees, using a parent/child (or category/sub/subsub) is not the best method. Although it does work, it usually requires multiple queries and recursive functions for display. A better approach is to use the nested set which is made for exactly this purpose.
这篇关于如何让第一级类别只显示一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!