0

I have this following result in my query: Query Result

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.'
                            )
                        )
    );
}
2
  • Why'd you remove your PHP code? Commented Aug 28, 2017 at 22:50
  • @Don'tPanic I rolled it back. Commented Aug 28, 2017 at 23:08

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, Your answer helped me a lot, I made a small change with the variable type is a row.
Oops, yep, thanks for catching that. (That's why we should try to avoid posting answers without testing them.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.