从php中的mysql查询创建2D数组

时间:2017-08-28 22:41:48

标签: php mysql arrays

我的查询中有以下结果: Query Result

我试图在php中创建这样的数组:

[
    {
        "software_version": "1.0",
        "version_date": "10/08/2016",
        "changelog": [
            {
                "type": "IMP",
                "description": "Initial version."
            }
        ]
    },
    {
        "software_version": "1.0.1",
        "version_date": "27/07/2017",
        "changelog": [
            {
                "type": "ADD",
                "description": "HostPanel update manager."
            },
        {
                "type": "ADD",
                "description": "Hook OnDaemonMinute."
            }
        ]
    }
]

我需要将结果与software_version行合并。 任何帮助表示赞赏。

我的PHP代码:

$changelog = array();
foreach ($result as $r) {
    $changelog[] = array(
        'software_version' => $r['software_version'],
        'version_date' => $r['version_date'],
        'changelog' => array(
                            array(
                                'type' => 'IMP', // help
                                'description' => 'Initial version.'
                            )
                        )
    );
}

1 个答案:

答案 0 :(得分:1)

密钥是在构建时使用软件版本作为$changelog中的密钥。

$changelog = array();
foreach ($result as $r) {

    // get the version (just to make the following code more readable)
    $v = $r['software_version'];

    // create the initial entry for the version if it doesn't exist yet
    if (!isset($changelog[$v]) {
        $changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']];
    }

    // create an entry for the type/description pair
    $change = ['type' => $r['type'], 'description' => $r['description']];

    // add it to the changelog for that version
    $changelog[$v]['changelog'][] = $change;
}

在JSON编码之前,您需要使用array_values重新索引$changelog,以便生成您想要的JSON数组输出。

$changelog = array_values($changelog);