在一个项目上通宵达旦,我的大脑一片空白……真的很简单的问题:
我有两个 MySQL 表,产品和类别。每个产品都属于一个类别。每个类别都有几种产品。
SELECT
p.uid as product_uid, p.name_NL as product_name, p.price as product_price,
c.uid as category_uid, c.name_NL as category_name
FROM
product p, category c
WHERE
p.category_uid = c.uid
这让我对各自类别中的所有产品有了一个很好的概览。我的问题是关于在页面上输出这些数据。我的目标是:
<h1>Category name</h1>
<p>Product in this category</p>
<p>Other product in this category</p>
<h1>Next category</h1>
<p>Product in next category</p>
我脑子里一片空白。如何才能做到这一点?
我想避免进行子查询(如果可能的话)。
亲切的问候,
中号
最佳答案
如何添加 ORDER BY category_uid
以便产品在您的 SQL 查询中按类别排序。然后使用 PHP,遍历每个产品(行),当您遇到新类别时,添加一个新标题。
示例:
<?php
// ...
$previous_category_uid = null;
// Loop through each row.
while ( $row = $result->fetch_assoc() )
{
// If the category UID is not the same as the one from the previous row, add a header.
if ( $previous_category_uid != $row['category_uid'] )
{
echo '<h1>' . $row['category_name'] . '</h1>';
$previous_category_uid = $row['category_uid'];
}
}
此方法的好处是您不必嵌套查询。一个查询就足够了。
关于php - PHP 中加入的 MySQL 结果的排序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541864/