之前我已经问了一个类似的问题,但我尝试将其改编为我的代码,但效果不佳。
我有以下代码在PHP中绘制表格,我想在检测到PRODUCT
更改时显示PRODUCT
总计,我尝试执行以下操作,但它显示了{每个TOTAL
开头的{1}}行,并没有很好地累计
变量PRODUCT
,GOLD
是动态的,即可能有没有NORMAL
的表,就像其他没有GOLD
的表一样:
这是我的代码:
NORMAL
要查看其工作原理,请复制并粘贴以下页面中的代码:
我希望有人可以帮助我。
答案 0 :(得分:0)
可能你正在寻找像这样的东西
<?
$harvest = Array (
Array (
'PRODUCT' => 'ROSE' ,
'VARIETY' => 'ADELE',
'GOLD' => 160,
'NORMAL' => 0 ,
'TOTAL' => 160
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ALESSO' ,
'GOLD' => 1320 ,
'NORMAL' => 550,
'TOTAL' => 1870
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ANASTACIA' ,
'GOLD' => 440 ,
'NORMAL' => 150 ,
'TOTAL' => 590
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1' ,
'GOLD' => 420 ,
'NORMAL' => 120 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1',
'GOLD' => 440 ,
'NORMAL' => 100 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2',
'GOLD' => 640,
'NORMAL' => 0,
'TOTAL' => 640
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2' ,
'GOLD' => 440,
'NORMAL' => 440,
'TOTAL' => 880
)
);
//You will endup with a products array indexed by product name
$products = [];
$general = Array('GOLD' => 0,'NORMAL' => 0, 'TOTAL' => 0);
foreach ($harvest as $items) {
$general["GOLD"] += $items["GOLD"];
$general["NORMAL"] += $items["NORMAL"];
$general["TOTAL"] += $items["TOTAL"];
if (array_key_exists($items["PRODUCT"],$products)){
$products[$items["PRODUCT"]]["TOTALS"]["GOLD-TOTAL"] += $items["GOLD"];
$products[$items["PRODUCT"]]["TOTALS"]["NORMAL-TOTAL"] += $items["NORMAL"];
$products[$items["PRODUCT"]]["TOTALS"]["TOTAL"] += $items["TOTAL"];
array_push($products[$items["PRODUCT"]],$items);
}
else{
$totals=[];
$totals["GOLD-TOTAL"] = 0;
$totals["NORMAL-TOTAL"] = 0;
$totals["TOTAL"] = 0;
$totals["NAME"] = $items["PRODUCT"];
$products[$items["PRODUCT"]]=[$items];
$products[$items["PRODUCT"]]["TOTALS"] = $totals;
}
}
&GT;
<table>
<thead>
<th>PRODUCT</th>
<th>VARIETY</th>
<th>GOLD</th>
<th>NORMAL</th>
<th>TOTAL</th>
</thead>
<tbody>
<?foreach ($products as $product) {
foreach ($product as $item){
if (array_key_exists("PRODUCT",$item)){
?>
<tr>
<td><?print($item["PRODUCT"])?></td>
<td><?print($item["VARIETY"])?></td>
<td><?print($item["GOLD"])?></td>
<td><?print($item["NORMAL"])?></td>
<td><?print($item["TOTAL"])?></td>
</tr>
<?}}?>
<tr>
<td>Total <? print($product["TOTALS"]["NAME"])?></td>
<td></td>
<td><? print($product["TOTALS"]["GOLD-TOTAL"])?></td>
<td><? print($product["TOTALS"]["NORMAL-TOTAL"])?></td>
<td><? print($product["TOTALS"]["TOTAL"])?></td>
</tr>
<?}?>
<tr>
<td>TOTAL GENERAL</td>
<td></td>
<td><?print($general["GOLD"])?></td>
<td><?print($general["NORMAL"])?></td>
<td><?print($general["TOTAL"])?></td>
</tr>
</tbody>
</table>