2016-12-01 91 views
1

我有這種問題。下面是我的代碼,只計算特定鍵的總JSON值

$json = json_decode($result, true); 
echo '<pre>'; 
foreach($json['campaigns'] as $campaign) 
{ 
    print_r(array('campaign_id'=>$campaign['id'], 
    'campaign_name'=>$campaign['settings']['title'], 
    'emails_sent'=>$campaign['emails_sent'])); 
} 
$sum = array('emails_sent'=>$campaign['emails_sent']); 
print_r('Total Email Sent: ' . array_sum($sum)); 
exit(); 

和輸出就像下面,

Array 
(
    [campaign_id] => bb50c7bb13 
    [campaign_name] => Campaign #1 
    [emails_sent] => 3 
) 
Array 
(
    [campaign_id] => 6b8194db96 
    [campaign_name] => Campaign #2 
    [emails_sent] => 4 
) 
Array 
(
    [campaign_id] => be9f2aed3e 
    [campaign_name] => Campaign #3 
    [emails_sent] => 0 
) 
Array 
(
    [campaign_id] => eb48c292cb 
    [campaign_name] => Campaign Scheduler #4 
    [emails_sent] => 0 
) 
Total Email Sent: 0 

正如你所看到的,我想計數[「emails_sent」]總數。因此,對於我的情況,['emails_sent']的總值是7.爲什麼輸出顯示爲0?

+0

只是使用'array_count_values()'來實現這一派。 –

+0

[PHP的 - 計數特定數組值]的可能重複(http://stackoverflow.com/questions/11646054/php-count-specific-array-values) –

+0

@FrayneKonok我試過使用array_count_values()它返回數組。我使用法比奧的解決方案,它正在工作。順便說一句,謝謝你的幫助。有新的知識:) – JunieL

回答

1

你可以只總結您的電子郵件,而迭代

$json = json_decode($result, true); 
$sum = 0; 
echo '<pre>'; 
foreach($json['campaigns'] as $campaign) { 
    print_r(array('campaign_id'=>$campaign['id'], 
    'campaign_name'=>$campaign['settings']['title'], 
    'emails_sent'=>$campaign['emails_sent']));  
    $sum += $campaign['emails_sent']; 
} 
print_r('Total Email Sent: ' . $sum); 
//print Total Email Sent: 7 
exit(); 
+0

謝謝,這一個幫助。 – JunieL

+0

歡迎你 – Fabio