Search code examples
phparraysobjectsub-array

Convert array of objects to object with sub-arrays in PHP


I search around for a bit but found nothing that did exactly what I'm after nor anything that really aided me in acheiveing what I'd like.

I have data in this format from a DB:

[
    {
        "datetime": "20170208183021",
        "ping": "11.201858520507812",
        "download": "28129628.324328355",
        "upload": "65169139.37489863"
    },
    {
        "datetime": "20170208181514",
        "ping": "7.826685905456543",
        "download": "300487650.87967044",
        "upload": "128210163.86553746"
    },
    {
        "datetime": "20170208180034",
        "ping": "19.550085067749023",
        "download": "17300126.504837424",
        "upload": "16650978.464359928"
    }
]

I'd like to convert it all to this format:

{
    "datetime": [
        "20170208183021",
        "20170208181514",
        "20170208180034"
    ],
    "ping": [
        "11.201858520507812",
        "7.826685905456543",
        "19.550085067749023"
    ],
    "download": [
        "28129628.324328355",
        "300487650.87967044",
        "17300126.504837424"
    ],
    "upload": [
        "65169139.37489863",
        "128210163.86553746",
        "16650978.464359928"
    ]
}

I'm guessing the best way is to use map but I wasn't sure how. Any help would be appreciated.


Solution

  • Here's an working example. You don't need anything fancy, a simple foreach will do the trick.

    $json = <<<EOS
    [
        {
            "datetime": "20170208183021",
            "ping": "11.201858520507812",
            "download": "28129628.324328355",
            "upload": "65169139.37489863"
        },
        {
            "datetime": "20170208181514",
            "ping": "7.826685905456543",
            "download": "300487650.87967044",
            "upload": "128210163.86553746"
        },
        {
            "datetime": "20170208180034",
            "ping": "19.550085067749023",
            "download": "17300126.504837424",
            "upload": "16650978.464359928"
        }
    ]
    EOS;
    
    $array = \json_decode($json, true);
    $results = [
        'datetime' => [],
        'ping'     => [],
        'download' => [],
        'upload'   => [],
    ];
    
    foreach ($array as $value) {
        $results['datetime'][] = $value['datetime'];
        $results['ping'][]     = $value['ping'];
        $results['download'][] = $value['download'];
        $results['upload'][]   = $value['upload'];
    }
    
    $results = \json_encode($results, JSON_PRETTY_PRINT);
    echo $results;