2015-12-03 44 views
-1

我訪問一個JSON解碼陣列遍歷數組的特定按鍵與PHP

$orders = json_decode($response, true); 

然後被叫數據的陣列中,我會通過每個訂單並找到總鍵。

// 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) 
    } 

} 

回答

1

你可以簡單地做 -

$total = 0; 
foreach($orders as $key => $order) { 
    $total += $order['total']; // add up the total 
} 

echo $total; 

或者,如果您有最新或大於5.5.0PHP版本,那麼 -

echo array_sum(array_column($orders, 'total')); 
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; 
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.