仅计算特定键的总JSON值

时间:2016-12-01 06:24:12

标签: php 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

如您所见,我想计算[&#39; emails_sent&#39;]的总数。所以对于我的情况,[&#39; emails_sent&#39;]的总值是7.为什么输出显示0?

1 个答案:

答案 0 :(得分: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();