简体   繁体   中英

Create 2D-Array from mysql query in php

I have this following result in my query: 查询结果

I'm trying to create an array like this in 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."
            }
        ]
    }
]

I need to combine the result with the software_version row. Any help is appreciated.

My php code:

$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.'
                            )
                        )
    );
}

The key is to use the software version as a key in $changelog as you build it.

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

You'll need to use array_values to reindex $changelog before JSON encoding it in order to produce the JSON array output you're going for.

$changelog = array_values($changelog);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM