sscotti sscotti - 4 months ago 15
JSON Question

Recursively sorting a JSON array

I've looked a little and found an answer that partially does what I am interested in doing, see: Sorting a JSON array in PHP

I have some decoded JSON that looks like this, just a sample.

{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"

}
]
}


What I would like to do is sort everything alphabetically so that it is easier to read and uniform. So that what I would see is:

{
"accounts": [
{
"css": null,
"connected": 0,
"must_approve_upload": 0,
"password_expire": 90,
"settings": {

"link_external_whitelist": "",
"link_first_study_only": "0",
"other_ingress_tags": "",
"update_study_source_on_notify": "1"
},

"share_via_gateway": 0,
"vanity": "medpics"
}
],
"page": {
"more": 0,
"number": 1,
"rows": 5000,
}
"status": "OK"
}


Every element is sorted alphabetically. Is that possible ?

Answer

Pretty straightforward

$json = <<<JSON
{
    "status": "OK",
    "page": {
        "rows": 5000,
        "more": 0,
        "number": 1
    },
    "accounts": [
        {
            "connected": 0,
            "settings": {
                "link_first_study_only": "0",
                "update_study_source_on_notify": "1",
                "link_external_whitelist": "",
                "other_ingress_tags": ""
            },
            "must_approve_upload": 0,
            "css": null,
            "share_via_gateway": 0,
            "password_expire": 90,
            "vanity": "medpics"

        }
    ]
}
JSON;

$json = json_decode($json, true);

function ksort_recursive(&$array) {
    ksort($array);
    foreach ($array as &$value) {
        if (is_array($value)) {
            ksort_recursive($value);
        }
    }
}

ksort_recursive($json);

print_r($json);

Proof of solution here

https://3v4l.org/qUAA0

Comments