Jack022
Jack022

Reputation: 1257

Summing values from JSON file in PHP

I have a JSON file which looks like this:

[{
    "num": "37"
}, {
    "num": "79"
}, {
    "num": "21"
}, {

    "num": "12"
}, {
    "num": "90"
}]

I need my script to print the sum of these numbers, here is what I tried:

<?php 
$dati = file_get_contents('data.json');
$elementi = json_decode($dati, true);
$test = 'test';

$sum = 0;
foreach($elementi['num'] as $key=>$value)
{
   $sum+= $value;
}


?>

But I got the error:

Notice: Undefined index: num in C:\xampp\htdocs\index.php on line 32

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\index.php on line 32

I'm stuck here and I can't find a solution. Can someone please help me?

Upvotes: 0

Views: 737

Answers (3)

Samuel Su
Samuel Su

Reputation: 1

  • You can use function array_sum
  • php version with:PHP 5 >= 5.5.0
$sum = array_sum(array_column($elementi, 'num'));

Upvotes: 0

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

I would do

 $sum = array_sum(array_column($arr, 'num'));

But that is just me...

Result

239

Sandbox

Array column, sucks out all the values for "key" ('num' in this case) and creates an array like this:

   ["37", "79", ...]

Then Array Sum, will give you the sum of an array of numbers.

Upvotes: 4

RiggsFolly
RiggsFolly

Reputation: 94662

You should always start with a print_r() of the array if you are not sure of its shape and content.

foreach($elementi as $arr)
{
   $sum+= $arr['num'];
}

Upvotes: 1

Related Questions