将对象数组转换为具有 PHP 中子数组的对象

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

我四处搜索了一下,但没有找到完全符合我要求的东西,也没有找到任何真正帮助我实现我想要的东西。

我有来自数据库的这种格式的数据:

[
    {
        "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"
    }
]

我想将其全部转换成这种格式:

{
    "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"
    ]
}

我猜最好的方法是使用地图,但我不确定如何使用。任何帮助将不胜感激。

那是 JSON,因此假设您将其解码为数组:

$array = json_decode($json, true);

要动态构建它而不管有多少键,只需循环一个以获取键名并提取它们:

foreach($array[0] as $key => $val) {
    $result[$key] = array_column($array, $key);
}

绕远一点:

foreach($array as $values) {
    foreach($values as $key => $val)
    $result[$key][] = $val;
}

编码后为对象:

$array = json_encode($result);

这是一个工作示例。你不需要任何花哨的东西,一个简单的 foreach 就可以了。

$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;