Home > other >  How to map JSON object to specific array
How to map JSON object to specific array

Time:11-20

I want to map my JSON response to specific array construction.

Here is my JSON data in short:

    "code": 200,
    "unit": null,
    "data": [
        {
            "2022-11-16": 185.6159202
        },
        {
            "2022-11-17": 204.31997631
        }...]

I need help to map this data to have array structure just like look array below:

    Array ( 
    [0] => Array
        (   [date] => 2018-01-03
            [value] => 0.0002444 )
    [1] => Array
        (   [date] => 2018-01-04
            [value] => 0.0171476 ))

My code in PHP:

    $decoded = json_decode($json, true);
    $arr = $decoded['data'];

After that, the structure of the array looks like this, which is not quite what I expect:

    Array ( 
        [0] => Array ( [2018-01-03] => 0.0002444 ) 
        [1] => Array ( [2018-01-04] => 0.0171476 ))

CodePudding user response:

foreach($decoded_array as $arr){
        $result[] = array('date' => array_keys($arr)[0], 'value' => array_values($arr)[0])

}
  • Related