[英]display mysql data with group in every type in php
我的表結構如下:
tbl1
id prodid prodname height cost category
-----------------------------------------
1 1 Test 5 54 ABC
2 5 Test1 6 85 DEF
3 8 Test2 8 20 DEF
4 2 Test3 4 10 GHI
5 3 test4 8 58 ABC
6 4 Test5 84 878 ABC
tbl2
id(FK of pid) color intensity vibrance
-----------------------------------------
1 red 5 NA
5 pink 0.5 8 ..and so on
現在我希望輸出如下
ABC
----
Test ... & other parameters
test4 ... & other parameters
Test5 ... & other parameters
DEF
---
Test1 ... & other parameters
Test2 ... & other parameters
GHI
----
Test3 ... & other parameters
"SELECT tbl1.*,tbl2.* from tbl1 LEFT JOIN tbl2 on tbl1.prodid=tbl2.id;
我試圖顯示貓如下:
$category="";
foreach($all as $row){
if ($row['category'] != $category && !empty($row['category'])) {
echo $row['category']; $category=$row['category'];
}
echo $row['othercolumns'];
}
但這不是分組...每次都在重復。
您可以使用PDO ,通過PDOStatement :: fetchAll()函數中的PDO::FETCH_GROUP
選項可以為您提供一個不錯的功能。 首先,在查詢中,將category
第一列,如下所示:
SELECT tbl1.category, tbl1.* from tbl1 LEFT JOIN tbl2 on tbl1.pid=tbl2.id;
然后在PDO
運行查詢,並使用PDO::FETCH_GROUP
fetchAll
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
print_r($result);
//Result will be something like this:
Array (
[ABC] => Array
[0] => Array
(
[id] => 1,
[prodid] => 1,
[prodname] => "test",
[height] => 5,
[cost] => 54,
[category] => "ABC",
),
[1] => Array
(
...
),
....
),
[DEF] => Array
(
...
),
....
)
您可以選擇全部,而在PHP中獲取結果的時間只需搜索類別。
SQL查詢:
SELECT tbl1.*, tbl2.*, tbl2.id AS id2
FROM tbl1 AS tbl1
LEFT JOIN tbl2 AS tbl2 ON(prodid = id2)
PHP部分:
while ($row = mysqli_fetch_array($rows)){
// handle $row[category] using switch or ifs
then put each in array to display the html part
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.