如何使第一级类别仅显示一次? [英] How do I get the first level category to display only once?
问题描述
我在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.
这篇关于如何使第一级类别仅显示一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!