我有一个这样的数组:
Array
(
[0] => Array
(
[15] => Due
[50] => Due
)
[1] => Array
(
[20] => Cancelled
[30] => Due
)
)
我想以表格格式在父数组的基础上显示到期金额的添加,如下所示:
Orders DueAmount
0 65
1 95
我试过的代码:
<table border="1" cellpadding="5">
<thead>
<tr>
<th>Orders</th>
<th>DueAmount</th>
</tr>
</thead>
<tbody>
<?php
$tot = 0;
for ($i=0; $i < count($ar); $i++) { // $ar is the parent array
foreach ($ar[$i] as $key => $value) {
if ($value === "Due") {
$amt = $tot += $key;
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$amt."</td>";
echo "</tr>";
}
}
}
?>
</tbody>
</table>
上面的代码执行后,输出如下:
Orders DueAmount
0 15
0 65
1 95
我该如何解决这个问题?请帮助我。
更新 1:
在 vascowhile 的评论之后:我得到以下输出
Orders Due Amount
0 15
0 50
1 30
最佳答案
只需将回显部分移出 foreach 循环即可:
for ($i=0; $i < count($ar); $i++) { // $ar is the parent array
foreach ($ar[$i] as $key => $value) {
if ($value === "Due") {
$amt = $tot += $key;
}
}
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$amt."</td>";
echo "</tr>";
}
关于php - 数组值相加不当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896245/