我正在访问json解码数组
$orders = json_decode($response, true);
然后在一个名为DATA的数组中,我将浏览每个订单并找到Total键。
// access the common array
$orders = $orders['data'];
// access the total of each order
$sale1 = $orders[0]['total'];
$sale2 = $orders[1]['total'];
$sale3 = $orders[2]['total'];
$sale4 = $orders[3]['total'];
$sale5 = $orders[4]['total'];
$sale6 = $orders[5]['total'];
$sale7 = $orders[6]['total'];
然后我将它们相加以获得所有订单的总和。
// add up all orders to find total
echo $sale1 + $sale2 + $sale3 + $sale4 + $sale5 + $sale6
我无法弄清楚如何将其变成循环。
这是我的阵列:
array(3) {
[0]=>
array(53) {
["total"]=>
int(100)
}
[1]=>
array(53) {
["total"]=>
int(100)
}
}
答案 0 :(得分:1)
你可以做 -
$total = 0;
foreach($orders as $key => $order) {
$total += $order['total']; // add up the total
}
echo $total;
或者,如果您有最新版本或大于5.5.0
PHP
版本,则
echo array_sum(array_column($orders, 'total'));
答案 1 :(得分:0)
您可以使用for循环在$ orders中指定索引键。
$temp = json_decode($response, true);
$orders = $temp['data'];
$len = count($orders);
for($i=0; $i < $len; $i++)
{
$total += $orders[$i]['total'];
}
echo $total;
答案 2 :(得分:0)
假设您有以下数组
$arr = array('0'=>array("total"=>100),
'1'=>array("total"=>100),
'2'=>array("total"=>100),
'3'=>array("total"=>100),
'4'=>array("total"=>100),
'5'=>array("total"=>100),
'6'=>array("total"=>100));
并且您想使用循环添加值然后使用以下语句
$total = 0;
foreach($arr as $key=>$val)
{
$total += $val['total'];
}
echo $total;//it will return 700 which is total value.