JunieL JunieL - 7 days ago 4
JSON Question

Count total JSON value for only a specific key

i have this kind of problem. Below is my code,

$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();


and the output is like below,

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


As you can see, i want to count total number for ['emails_sent']. So for my case, the total value for ['emails_sent'] is 7. Why the output shows 0?

Answer

You can just sum your email sent while iterating

$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();