I have a couple of json files in a directory data
.
Each json file looks like below:
{
"id": "id_2021-04-01_1300",
"starttime": "13:00",
"endtime": "18:00",
"hours": 5
}
To count the sum of all hours
together from all json files, i have this code in php:
$files = glob('data/*.json'); // all json-files in array
foreach($files as $file) {
$hours_arrays[] = json_decode(file_get_contents($file), true);
}
$total_hours = 0;
foreach($hours_arrays as $key => $val) {
$total_hours = $val['hours'];
}
According to this code, $total_hours
should contain the sum of all the hours from all json files. But i got back 0
. What i am doing wrong?
CodePudding user response:
I just ran your code and it works fine. https://prnt.sc/1xzcibj. Debug that your files have correct path and you are recieving the content. Also check the parsed content of files in variable $hours_arrays
. It should look like variable on my screenshot
CodePudding user response:
I can’t comment on my account yet but I suspect you want to access it as an object
$val->hours
Rather than an array as the json shows an object not an array.
Edit : bad answer I didn’t see the true flag on json decode