2015-05-13 80 views
-5

我已經寫了PHP腳本,輸出從API以下特定條目的總和:獲取PHP數組

array(197) { 
    [0]=> 
    array(2) { 
    ["buyer_email"]=> 
    string(25) "*****@live.co.uk" 
    ["total"]=> 
    array(2) { 
     [0]=> 
     string(4) "0.10" 
     [1]=> 
     string(4) "6.41" 
    } 
    } 
    [1]=> 
    array(2) { 
    ["buyer_email"]=> 
    string(19) "*****@hotmail.com" 
    ["total"]=> 
    array(8) { 
     [0]=> 
     string(4) "7.00" 
     [1]=> 
     string(4) "7.50" 
     [2]=> 
     string(5) "10.14" 
     [3]=> 
     string(5) "17.69" 
     [4]=> 
     string(5) "10.14" 
     [5]=> 
     string(5) "10.14" 
     [6]=> 
     string(5) "10.14" 
     [7]=> 
     string(5) "10.14" 
    } 
    } 

這基本上示出了由每個用戶進行的購買。我想擁有所有用戶的購買總和。例如 "buyer_email": ****@live.co.uk, "total" : 6.51

我已經試過這個解決方案由Luca建議:

$json = '{"buyer_email":"****@live.co.uk","total":["0.10","6.41"]}'; 
$obj = json_decode($json); 
$total = $obj->{'total'}; 

$sumTotal = 0; 
for($i = 0; $i < count($total); $i++){ 
$sumTotal += $total[$i]; 
} 

print $sumTotal; 

它適用於個人入境,但不是當有不止一個?

+4

你需要用json_decode然後解析,創建總結和再編碼的邏輯。 – ErasmoOliveira

回答

1

的工作:

$json = '{"buyer_email":"****@live.co.uk","total":["0.10","6.41"]}'; 
$obj = json_decode($json); 
$total = $obj->{'total'}; 

$sumTotal = 0; 
for($i = 0; $i < count($total); $i++){ 
$sumTotal += $total[$i]; 
} 

print $sumTotal; 
+0

這似乎並不奏效。也許是因爲我有不止一個這種類型的數組?如同更多的買家一樣。 –