Home > Net >  How to count sum of values from json objects in certain subdirectories seperately
How to count sum of values from json objects in certain subdirectories seperately

Time:11-26

I have 3 directories named september, october and november in the maindirectory 2021. In all these 3 directories are json files which look like this:

{
    "id": "id_2021-09-05_2200",
    "date": "2021-09-05",
    "guests": 32 // total guests for that day
}

For every month, i need the sum of all guests for that month. ( count all guests from all the json files in that month together).

I have this code so far but i get stuck in counting for each month:

$monthdirs = array_filter(glob('data/2021/*'), 'is_dir'); // read all month-dirs in year 2021
foreach($monthdirs as $monthdir) {
    $monthfiles = glob($monthdir.'/*.json');    // all json files in a specific month
}
foreach($monthfiles as $monthfile) {
        $arr[] = json_decode(file_get_contents($monthfile),true); // php assoc array
        foreach($arr as $key => $val) {
            $tot_guests_monthes[]  = $val['guests'];    // new array from each month with the sum of guests from all the json files in that month 
        }
}
foreach($tot_guests_monthes as $tot_guests_month) {
    echo $tot_guests_month.'<br />';
}

I think in the 2nd foreach loop i am doing something wrong. My final output should be 3 values, something like:

200 // all guests september
300 // all guests october
400 // all guests november

CodePudding user response:

$...[] = is basically a array_push, which means that $tot_guests_monthes[] = $val['guests']; will create a new element for each element of $arr of each $monthfile instead of summing.

Summing all values in a month and then adding them to $tot_guests_monthes should work:

$tot_guests_monthes = [];

$monthdirs = array_filter(glob('data/2021/*'), 'is_dir'); // read all month-dirs in year 2021
foreach($monthdirs as $monthdir) {
    $monthfiles = glob($monthdir.'/*.json');    // all json files in a specific month
    
    $sum = 0;
    foreach($monthfiles as $monthfile) {
        $arr = json_decode(file_get_contents($monthfile), true);
        $sum  = $arr['guests'];
    }
    $tot_guests_monthes[] = $sum;
}

foreach($tot_guests_monthes as $tot_guests_month) {
    echo $tot_guests_month.'<br />';
}
  • Related