我有一个foreach循环,我正在运行JSON数据。 JSON中的一个值是数字:
{
"apiVersion": "0.1",
"data": {
"offset": 0,
"limit": 50,
"count": 50,
"total": 783,
"reports": [
{
"type": "ROOM_CHARGE",
"data": {
"datetime": "2014-11-10T11:08:08-08:00",
"originator": "265a",
"roomNumber": "265",
"chargeItem": "Premium Services",
"chargeAmountCents": 495
}
},
{
"type": "STB_EVENT_TIMED",
"data": {
"datetime": "2014-11-10T10:38:20-08:00",
"originator": "242b",
"roomNumber": "242",
"eventItem": "Watched movie 31008",
"duration": "P0Y0M0DT0H7M50.827S"
}
},
{
"type": "ROOM_CHARGE",
"data": {
"datetime": "2014-11-10T09:35:37-08:00",
"originator": "540a",
"roomNumber": "540",
"chargeItem": "Premium Services",
"chargeAmountCents": 495
}
},
您会注意到"ROOM_CHARGE"
上方"chargeAmountCents": 495
。我想运行我的foreach循环并将每个数字加在一起:
请注意我的代码$total
。我基本上想要将所有房间费用加在一起,然后在最后回显总计。我可以自己格式化数字,我只是遇到了"+="
运算符的问题而不确定它是否应该以这种方式使用?当我"495"
时,我一直收到echo $total
。
<?php foreach($output1['data']['reports'] as $reporting): ?>
<?php if($reporting['type'] == "ROOM_CHARGE") : ?>
<tr>
<td><?php echo 'Room Charge'; ?></td>
<td><?php echo substr($reporting['data']['datetime'], -26, 10) ?></td>
<td><?php echo substr($reporting['data']['datetime'], -14, 8) ?></td>
<td><?php echo ($reporting['data']['roomNumber']) ?> </td>
<td><?php echo ($reporting['data']['originator']) ?> </td>
<td><?php echo ($reporting['data']['chargeItem']) ?></td>
<td><?php echo number_format(($reporting['data']['chargeAmountCents'])/100, 2, '.', ',') ?></td>
<td>-</td>
<?php $total = ""; ?>
<?php $total += ($reporting['data']['chargeAmountCents']) ?>
</tr>
答案 0 :(得分:0)
在你的循环中,你正在做<?php $total = ""; ?>
。因此,每次循环时,您都重置总数。
您需要设置$total
(至0
,因为它是一个数字)在循环之外。
<?php $total = 0; ?>
<?php foreach($output1['data']['reports'] as $reporting): ?>
<?php if($reporting['type'] == "ROOM_CHARGE") : ?>
<tr>
<td><?php echo 'Room Charge'; ?></td>
<td><?php echo substr($reporting['data']['datetime'], -26, 10) ?></td>
<td><?php echo substr($reporting['data']['datetime'], -14, 8) ?></td>
<td><?php echo ($reporting['data']['roomNumber']) ?> </td>
<td><?php echo ($reporting['data']['originator']) ?> </td>
<td><?php echo ($reporting['data']['chargeItem']) ?></td>
<td><?php echo number_format(($reporting['data']['chargeAmountCents'])/100, 2, '.', ',') ?></td>
<td>-</td>
<?php $total += ($reporting['data']['chargeAmountCents']) ?>
</tr>