我有一个包含以下记录的表:
product_id | title | category
------------------------------------
1 | apple | mobile
2 | android | mobile
3 | dell | desktop
4 | hp | desktop
以及以下查询:
$sql = "SELECT product_id, title, category FROM products ORDER BY category";
$stmt = $db->prepare($sql);
$stmt->execute();
while($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $results["product_id"];
echo $results["title"];
echo $results["category"];
}
问题是如何拆分结果并显示按类别排序的列表中的所有记录,如下所示:
桌面
答案 0 :(得分:1)
获取结果集后对记录进行分组:
$products = array();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$products[$results['category']][] = array(
'product_id' => $results['product_id'],
'title' => $results['title']
);
}
foreach ($products as $category => $productList)
{
echo $category . '<br>';
foreach ($productList as $product)
{
echo $product['title'] . '<br>';
}
echo '<hr />';
}
答案 1 :(得分:0)
使用SELECT * FROM products GROUP BY category ORDER BY title
答案 2 :(得分:0)
在对商品(ORDER BY category, title
)进行排序后,请执行以下操作:
$last_category = "";
while(/* get a row here */) {
if( $last_category != $row['category']) {
if( $last_category != "") echo "</ul>";
echo "<ul>";
$last_category = $row['category'];
}
echo "<li>".$row['title']."<li>";
}
if( $last_category != "") echo "</ul>";
答案 3 :(得分:0)
SELECT * FROM产品ORDER BY类别。这是使用类别排序,您的示例输出文件似乎与您尝试做什么不同?