首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从php中的mysql查询创建2D-Array

从php中的mysql查询创建2D-Array
EN

Stack Overflow用户
提问于 2017-08-28 22:41:48
回答 1查看 28关注 0票数 0

在我的查询中有以下结果:

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

代码语言:javascript
运行
复制
[
    {
        "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代码:

代码语言:javascript
运行
复制
$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.'
                            )
                        )
    );
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-28 22:55:11

关键是在构建$changelog时将软件版本作为密钥使用。

代码语言:javascript
运行
复制
$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数组输出。

代码语言:javascript
运行
复制
$changelog = array_values($changelog);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45928295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档