Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add up all int() values from a PHP array

Tags:

json

arrays

php

int

I've have a JSON file that I am parsing using json_decode() which outputs the contents of the JSON files as an array, This is a sample of the data output:

array(1) {
  ["petition"]=>
    array(2) {
      ["postal_districts"]=>
        array(2257) {
          ["DH4"]=>
          int(12)
          ["BT5"]=>
          int(14)
          ["WA9"]=>
          int(72)
          ["EH17"]=>
          int(5)
       }
    }
}

I am wanting to add up all the int() values from under "postal_districts" but at the moment I'm at a loss as to how I can achieve this.

Any help is greatly appreciated.

like image 669
Oliver Avatar asked Dec 05 '25 05:12

Oliver


2 Answers

If they are all ints, you can try:

$sum = array_sum($arr['petition']['postal_districts']);

(see if array_sum helps)

If not, filter them first:

$ints = array_filter($arr['petition']['postal_districts'], 'is_int');
$sum = array_sum($ints);
like image 159
nice ass Avatar answered Dec 07 '25 06:12

nice ass


$sum = 0;
foreach($array['petition']['postal_districts'] as $val)
    $sum += $val;
echo $sum;

Do you mean it?

like image 30
Winston Avatar answered Dec 07 '25 05:12

Winston