我有一個包含這些欄位的 mysql 表:
series_id, series_color, product_name
在輸出中,我想按部分列出數據,每個 series_id 一個部分,如下所示:
series_id
A12 Series Product - Milk - Tea - sugar - water B12 Series Product - Water - Banana - Cofee - Tea
按 series_id 對結果進行排序,因此具有相同值的所有產品將放在一起。
$stmt = $pdo->prepare("SELECT series_id, product_name FROM yourTable ORDER BY series_id"); $stmt->execute();
然後,在顯示結果時,顯示系列標題並在其發生變更時啟動新的 :
$last_series = null; echo "<ul>\n"; while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { if ($row['series_id'] != $last_series) { if ($last_series) { echo "</ul></li>\n"; } echo "<li>" . $row['series_id'] . " Series Product\n"; echo "<ul>\n"; $last_series = $row['series_id']; } echo "<li>" . $row['product_name'] . "</li>\n"; } if ($last_series) { echo "</li>\n"; } echo "</ul>\n";
按
series_id
對結果進行排序,因此具有相同值的所有產品將放在一起。然後,在顯示結果時,顯示系列標題並在其發生變更時啟動新的
: