1.使用JOIN
做,在單個查詢(最佳解決方案): -
$query = "Select Dishes.*,Category.id as cat_id from Category LEFT JOIN Dishes on Dishes.cat_id = Category.id";
$Listings = $mysqli->query($query);
$AllDishes = array();
while($row = $Listings->fetch_assoc()) {
$AllDishes[$row['cat_id']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
print_r($AllDishes);
如果你想在你的編碼方式做那麼: -
2.Distinguish他們基於類別的id
: -
$query = "Select id from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row['id'];
}
foreach ($idlist as $id){
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$id][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
3.Distinguish他們基於類別的name
: -
$query = "Select id,category_name from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row;
}
foreach ($idlist as $id){
$id = $id['id'];
$category_name = $id['category_name']; //change column-name
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$category_name][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
注: - 請更改列名在第三個解決方案中(因爲我不知道你需要存儲什麼列名稱類別名稱)。
什麼是您用來保存類別名稱的字段?請告訴 –
您的問題出現在'$ AllDishes [] ='中,因爲您不斷爲每個類別添加「$ AllDishes」變量。您必須爲每次迭代「更改」存儲變量。 – insider