Home > Blockchain >  how to get values from json obj in php foreach loop
how to get values from json obj in php foreach loop

Time:12-09

I have a couple of json files and each json file looks like below:

{
    "id": "id_1638974137049",
    "weeknr": 48,
    "dayhours": 5,
    "tvt": 1.25
}

Another file:

{
    "id": "id_1638974137050",
    "weeknr": 48,
    "dayhours": 6,
    "tvt": 1.50
}

and another:

{
    "id": "id_1638974137023",
    "weeknr": 48,
    "dayhours": 7,
    "tvt": 1.75
}

Now i want to make a table as output in which the weeknr, the dayhours and the tvthours for that week. This is what i have so far:

$files = glob('data/*.json'); // all json files in array
foreach($files as $file) {
        $objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array             
    }
foreach($objs as $key => $val) {
    $weeknr = $val['weeknr']; // weeknr

    $array_dayhours[$weeknr]  = $val['dayhours']; // sum of all the dayhours from that week
    $array_tvthours[$weeknr]  = $val['tvt']; // sum of all the tvt hours from that week
    // i dont know how to handle this further to create a new array which contains per week the dayhours and tvt hours 
}

I need an output (in a table) like this:

weeknr   tot dayhours   tot tvt hours
48       18              4.5
49       20              6.5
50       24              5.5

CodePudding user response:

You can do something like this

$files = glob('data/*.json'); // all json files in array
$objs = [];
//array to store all data
$weeksData = [];

foreach($files as $file) {
        $objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array             
}

foreach($objs as $key => $val) {
    
    //using weeknr as array key and pushing it to weekData array
    $weeksData[$val['weeknr']] = [
        'dayhours' => ($weeksData[$val['weeknr']]['dayhours'] ?? 0)    $val['dayhours'],
        'tvt' => ($weeksData[$val['weeknr']]['tvt'] ?? 0)   $val['tvt']
    ];
}

CodePudding user response:

<?php
$files = glob('data*.txt'); // all json files in array
foreach($files as $file) {
    $objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array
}
$arrayResult=[];
foreach($objs as $key => $val) {
    $weeknr = $val['weeknr']; // weeknr
    if(isset($arrayResult[$weeknr]) && is_array($arrayResult[$weeknr]))  // If already exist
        $arrayResult[$weeknr]=["weeknr"=>$val['weeknr'],"dayhours"=>$arrayResult[$weeknr]["dayhours"] $val['dayhours'], "tvt"=>$arrayResult[$weeknr]["tvt"] $val['tvt']];
    else // for new entry
        $arrayResult[$weeknr]=["weeknr"=>$val['weeknr'],"dayhours"=>$val['dayhours'], "tvt"=>$val['tvt']];
}

You can use $arrayResult for your printing

  • Related