我有一个清单产品(包括类别和数量)
$html = "";
foreach ($products as $product) {
$html .= $product->category;
$html .= $product->name;
$html .= $product->quantity;
}
echo $html;
按照此列表
Category | Product | Quantity
Timsum T1 10
Timsum T2 20
Timsum T3 30
Sauces S1 5
Sauces S2 15
如何汇总组并显示每个类别的最后一行
Category | Product | Quantity
Timsum T1 10
Timsum T2 20
Timsum T3 30
**Sum Timsum 60**
Sauces S1 5
Sauces S2 15
**Sum Sauces 20**
答案 0 :(得分:1)
按类别名称排序结果集,然后使用临时变量:
$qty = 0;
$last_cat = null;
foreach ($products as $product) {
if ($product->category != $last_cat && $last_cat) {
echo "**Sum $last_cat $qty\n";
$qty = 0;
$last_cat = $product->category;
}
printf("%s\t%s\t%s\n",
$product->category, $product->name, $product->quantity);
$last_cat = $product->category;
$qty += $product->quantity;
}
答案 1 :(得分:1)
添加$sum
变量来记录累积的数量,并在类别移动时制作一些条件来跟踪该作业:
$html = "";
$first_iteration = FALSE;
$sum = 0;
foreach ($products as $product) {
if (!$first_iteration)
{
$first_iteration = TRUE;
$temp_category = $product->category;
}
if ($temp_category != $product->category)
{
html .= "**".$temp_category;
html .= $sum;
$sum = 0;
$temp_category = $product->category;
}
$html .= $product->category;
$html .= $product->name;
$html .= $product->quantity;
$sum += (integer) $product->quantity;
}
html .= "**".$temp_category;
html .= $sum;
echo $html;