lundi 21 juin 2021

Refactor the JSON object in Laravel

Here's my JSON:

[
    {
        "ID": 1,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-05 07:05:29",
        "VALUE": "30"
    },
    {
        "ID": 4,
        "SOURCEID": 2,
        "TIMESTAMP": "2020-04-05 07:05:17",
        "VALUE": "40"
    },
    {
        "ID": 3,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-06 12:04:59",
        "VALUE": "35"
    },
    {
        "ID": 5,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-06-17 12:01:32",
        "VALUE": "1"
    },
    {
        "ID": 6,
        "SOURCEID": 2,
        "TIMESTAMP": "2021-06-17 13:55:29",
        "VALUE": "2"
    }
]

I need to refactor the JSON like

I need JSON to be refactor based on timestamp and source id and JSON is dynamic like a number of source id present in the given JSON there are two ids that is 1 and 2. Below I gave the expected output.

I need a Unique time stamp in a separate array-like

 [2020-04-05,2020-04-06,2020-06-17,2021-06-17]
    { "sourceid: 1, "data":[30,35,1,0], }, { "sourceid": 2, "data":[40,0,0,2], }

Note: The value fills according to the date. Other it should fill as 0.

I have tried like this :

    `$data=json_decode($result);

    $timestamp=[];
    $dataList=[];
    foreach ($data as $value){

        $date=\Carbon\Carbon::parse($value->TIMESTAMP)->toDateString();

        if(!in_array($date, $timestamp, true)){
            array_push($timestamp, $date);
        }
        
        if(isset($dataList[$value->SOURCEID])){
            array_push($dataList[$value->SOURCEID]['data'],$value->VALUE);
        } else{
            $dataList[$value->SOURCEID]=[
                'SOURCEID'=>$value->SOURCEID,
                'data'=>[$value->VALUE]
            ];
        }
    }
    dump($timestamp);
    dump($dataList);` 

But it produce like

{ "sourceid: 1, "data":[30,35,1], }, { "sourceid": 2, "data":[40,2]}

but I need like

{ "sourceid: 1, "data":[30,35,1,0], }, { "sourceid": 2, "data":[40,0,0,2] }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3zJF0DC
via IFTTT

Aucun commentaire:

Enregistrer un commentaire