Reputation: 1257
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
Reputation: 1
array_sum
$sum = array_sum(array_column($elementi, 'num'));
Upvotes: 0
Reputation: 21661
I would do
$sum = array_sum(array_column($arr, 'num'));
But that is just me...
Result
239
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
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