【发布时间】:2017-12-10 19:33:55
【问题描述】:
这是我的数据库结构
Categories table
id title
-----------
1 cars
2 city
3 names
------------
subcategory table
id cat_id title
1 1 BMW
2 1 Kia
3 2 Moscow
4 1 Passat
5 2 London
6 3 John
----------------------
现在我像这样使用 foreach 获取类别和打印:
$myquery = query("Select * From categories"); // These functions only for example
$array = mysql_fetch_array($myquery); // These functions only for example
foreach($array as $cat){
echo $cat['title'];
echo "<br />";
// in here must be again foreach or other loop to print subcats belongs to
// this category id, otuput like this:
// Cars
// -- BMW
// -- KIA
// -- Passat
// City
// -- Moscow and etc...
}
我不想在 foreach 中使用新查询,我想使用 mysql JOIN 来执行此操作,但我不知道如何操作。谁能帮帮我?
【问题讨论】:
-
创建join语句并按category.id排序,然后在循环中检查你是否已经拥有那个即将到来的类别->只打印子类别。如果您还没有主要类别,也请打印出来。
-
或者你先把它全部放在一个二维数组中(以 category.id 作为主键)。