这是我的数据库结构
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 来做到这一点,但我不知道怎么做。谁能帮帮我?
最佳答案
mysql 连接将是:
SELECT subcategory.*, categories.title as cat_title FROM subcategory JOIN categories ON subcategory.cat_id = categories.id ORDER BY subcategory.cat_id;
这将为您提供一个表格,其中包含所有带有附加类别信息的子类别项目
那么 php 看起来像这样:
$result = mysql_fetch_array($myquery);
foreach($result as $row){
// this is the category name
print($row['cat_title']);
// the title of the subcategory item
print($row['title']);
}
如果您不想每次都打印类别名称,请查看 this发布如何按一列对表格进行排序。将数组更改为多维数组,以便可以使用两个 foreach。 Php 看起来像这样:
$categories = array();
// result comes from the SELECT
foreach($result as $row){
if(isset($row['cat_title']) && !empty($row['cat_title'])){
if(!isset($categories[$row['cat_title']]) || !is_array($categories[$row['cat_title']])){
$categories[$row['cat_title']] = array();
}
array_push($categories[$row['cat_title']], $row);
}
}
现在您可以使用 foreach 遍历类别:
foreach($categories as $category => $items){
print($category);
foreach($items as $item){
print("\t".$item);
}
}
关于Php 使用 mysql 查询按类别 ID 获取子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47742652/