根本不要使用数组。你有一个二维数组,可以直接建表:
SELECT client.id, client.name, product.name as productname, SUM(order.quantity) AS qty
FROM client CROSS JOIN product
LEFT JOIN order ON ( order.product_id = product.id AND order.client_id = client.id)
GROUP BY client.id, product.id ORDER BY client.name, product.code;
这将为每个客户和产品输出一个单元格,如果该(客户,产品)和订单之间没有 JOIN,则可能为 NULL。
然后你可以在 PHP 中迭代表(当然你可以将它保存在一个多维数组中,使用客户端和产品 ID 作为键):
print "<table>";
$customer_id = -1;
while($tuple = SQLFetchTuple($exec))
{
if ($tuple['id'] != $customer_id)
{
if (-1 != $customer_id)
print "</tr>"; // Close previous row
print "<tr><td>{$tuple['name']</td>"; // Output row header
$customer_id = $tuple['id'];
}
if ($tuple['qty'])
print "<td>{$tuple['qty']</td>";
else
print "<td>-</td>";
}
print "</table>";