Preserve JSON arrays while sorting Preserve JSON arrays while sorting json json

Preserve JSON arrays while sorting


You could use JavaScript for doing the sorting on click, and use PHP only for passing the JSON to it.

After you provided the HTML structure you want to display the list in, I updated this answer to use div elements for the records and p elements for the fields.

We could replace the select list, for selecting the sort order, by two buttons.

Here is the PHP code:

<?php$homepage = array();  $homepage[]= '{     "info":{        "collection":[           {              "Name":"Charlie",            "ID":"13"         },         {              "Name":"Emma",            "ID":"9"         }      ]   }}';  $homepage[] = '{     "info":{        "collection":[           {              "Name":"Bob",            "ID":"10"         }      ]   }}';$data = array();foreach ($homepage as $homepage2) {    $tmp=json_decode($homepage2, false);    $data = array_merge($data,$tmp->info->collection);}?><div id="container"></div><button id="sort1">Alphabetical</button><button id="sort2">High to Low</button><script>    var collection = <?=json_encode($data)?>;    function populate(compareFunc) {        collection.sort(compareFunc);        var container = document.getElementById('container');        container.innerHTML = '';        collection.forEach(function (key) {            var div = document.createElement("div");            div.className = "inventory";            var span = document.createElement("span");            span.textContent = key.ID;            div.appendChild(span);            span = document.createElement("span");            span.textContent = key.Name;            div.appendChild(span);            container.appendChild(div);        });    }    var populateById = populate.bind(null, function (a, b) {        return a.ID - b.ID;    });    var populateByName = populate.bind(null, function (a, b) {        return a.Name.localeCompare(b.Name);    });    document.getElementById("sort1").addEventListener('click', populateByName);    document.getElementById("sort2").addEventListener('click', populateById);    document.addEventListener('DOMContentLoaded', populateById);</script>

For the sample data this will result in the following JavaScript/HTML, which you can test here: