10

I have two JSON arrays coming from an external website. I sort and merge the two arrays, decode them and then sort them from highest to lowest by ID.

Currently, when the option 'alphabetical' is clicked, ?sort=alphabetical is added onto the end of the URL and when the page has finished reloading, the JSON arrays are once again decoded and merged.

This is not my desired outcome: I do not want the JSON arrays to be decoded and merged again when the option is clicked - I simply want the already decoded and merged JSON arrays to be sorted alphabetically.


Arrays:

$homepage = array();  

$homepage[]= '{  
   "info":{  
      "collection":[  
         {  
            "Name":"Charlie",
            "ID":"7"
         },
         {  
            "Name":"Emma",
            "ID":"9"
         }
      ]
   }
}';  

$homepage[] = '{  
   "info":{  
      "collection":[  
         {  
            "Name":"Bob",
            "ID":"5"
         }
      ]
   }
}';

Sorting:

$data = array();
foreach ($homepage as $homepage2) {
    $tmp=json_decode($homepage2, false);
    $data = array_merge($data,$tmp->info->collection);
}

if(!empty($_GET['sort']) && $_GET['sort'] == 'alphabetical') {
    usort($data, function ($a, $b) {
        return strcmp($a->Name, $b->Name);
    });
}else{
    usort($data, function ($a, $b) {
        return $b->ID - $a->ID;
    });
}

echo'
<select onchange="location.href = this.value;">
    <option value="example.php?sort=alphabetical">Alphabetical</option>
</select>
';

foreach($data as $key) {
    echo'
    <a href="test.com">
    <p>'.$key->ID.'</p>
    <p>'.$key->Name.'</p>
    </a>
    ';
}  
11
  • Can you rephrase the question? I for one can't seem to decipher what you're getting at.
    – Jonnix
    Jun 16, 2016 at 15:16
  • 2
    @TheCodesee if you want to change the contents of the page without refreshing you'll almost certainly have to write some JavaScript to do so - unless you wanted to create another request to the server and replace the contents of the page. Jun 16, 2016 at 16:17
  • 1
    May I ask why you don't want to decode/merge the array of JSON strings again? It isn't a big performance problem and the only way to avoid this is storing the decoded/merged data somewhere (like a PHP session or DB), but that seems like it'll just bring on more problems than not.
    – Sam
    Jun 23, 2016 at 20:05
  • 1
    @Sam Good question. As I mentioned in my post, I am getting the json data from an external url (I posted an example of the json file in this question to make it easier to understand). I am worried that the server will block me if I make too many requests. Jun 23, 2016 at 20:06
  • 1
    Could you give the exact way how you output the ID and Name values? I don't suppose you just output them like that without HTML? Javascript-based solutions need to know the exact HTML structure you put them in.
    – trincot
    Jun 23, 2016 at 20:20

3 Answers 3

5
+50

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:

var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","ID":"10"}];

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);
span { margin-left: 5px }
div.inventory { border-bottom: 1px solid gray }
<div id="container"></div>

<button id="sort1">Alphabetical</button>
<button id="sort2">High to Low</button>

Note that I gave the three items different ID values than in your question, since otherwise the sort order would be the same for both ID and Name.

Using tables: alternative

There are nice JavaScript libraries which give much more features to represent data sets. Here is an example using jQuery with DataTables:

var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","ID":"5"}];

function populate() {
  var tbody = $('#collection>tbody');
  collection.forEach(function (key) {
    var row = $('<tr>');
    row.append($('<td>').text(key.ID));
    row.append($('<td>').text(key.Name));
    tbody.append(row);
  });
}

$(document).ready(function(){
  populate();
  $('#collection').DataTable();
});
<script src="http://code.jquery.com/jquery-1.12.3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

<table id="collection">
    <thead>
        <tr><th>ID</th><th>Name</th></tr>
    </thead>
    <tbody/>
</table>

The actual code is even smaller (not counting the included library) than a pure JavaScript solution would be with a basic table. But this has sorting up and down, filtering, pagination, nice styles, ...

3
  • Many thanks for your excellent response, I truly wasn't expecting it! I apologize for not making my question clearer. Rather than displaying the results in tables, I'm displaying them inside a div element. From your code, I have modified it to fit my needs: jsfiddle.net/jknj4uat/1 (could you please update your post) - thank you very much for your help :) Jun 24, 2016 at 17:13
  • I am happy to adjust my answer, but the HTML you now ask for in the question includes a and p tags, while the jsfiddle you point to only outputs the name, not the ID, and without those a and p tags. So it is different on almost all aspects. What exactly do you want? ;-)
    – trincot
    Jun 24, 2016 at 17:42
  • Anyway, I have updated my post. Note that it is better to use textContent than innerHTML when it concerns unformatted text. I've also used bind to create two flavours of the populate function, which now accepts as argument the function to sort with.
    – trincot
    Jun 24, 2016 at 18:00
2

There are several alternatives for this answer, so I will present a simple one:

Send the data already sorted, a default one, if the user made no choices. Then, set a function that sorts the data as needed, and redraws tables/divs/whatever you are using to present them.

As an quick example:

function sortAlpha(){
   for each (stuff in data){
      document.getElementById("aTable").textContent=data.StringRepresentation;
   }
}

Then a function for sortSize, sortEtc, etc... in each function, you clear a div content, and populate it again. This way, you do not need to request new content from servers

getElementById documentation

1
  • Yup, JS is the best (really the only, if a database isn't being used to store data) solution.
    – Sam
    Jun 23, 2016 at 20:20
0

There are multiple solutions in which you can achieve the desired results.

If you want it pure PHP way what you can do is save the data in PHP Sessions and retrive them as need.

Here is the trick comes, You create function to get the result data in which you pass single parameter whether you want to get the data from external URL or from your saved data.

Now, in your application whenever you want to refresh the saved data call the same function with parameter denoting to refresh the saved data in SESSIONS to get replaced with data from external source.

Using this method you can reuse the data you've already fetched from external source without re-fetching it every-time you reload the function.

You can make another function which will return true for all cases in which application has to re-fetch the resultset from external source.

I've written pseudo code for you to understand what I'm trying to convey,

Function check whether we've to re-fetch the result from external source:

function hasToRefreshResult() {
        if(/* CERTAIN CONDITIONS */) {
            return true;
        }
        return false;
    }

Couple of functions to get the data from local/external source according to the parameter passed:

    function getResultArray($getdatafromlocal) {
        if(!hasToRefreshResult() && $getdatafromlocal && array_key_exists("filertereddata",$_SESSION) && isset($_SESSION["filertereddata"])) {
            $data=$_SESSION["filertereddata"];
        } else {
            $data=getDataFromExternalURL();
        }

        if(!empty($_GET['sort']) && $_GET['sort'] == 'alphabetical') {
            usort($data, function ($a, $b) {
                return strcmp($a->Name, $b->Name);
            });
        } else {
            usort($data, function ($a, $b) {
                return $b->ID - $a->ID;
            });
        }

        return $data;
    }

    function getDataFromExternalURL() {
        /*****
           YOUR LOGIC TO GET DATA FROM EXTERNAL URL;
         *****/

        $data = array();
        foreach ($homepage as $homepage2) {
            $tmp=json_decode($homepage2, false);
            $data = array_merge($data,$tmp->info->collection);
        }
        $_SESSION["filertereddata"]=$data;
        return $data;
    }

I hope this will solve your issue strictly using PHP.

Also don't forget the write session_start(); at the top of the PHP file you will be using this functions.

9
  • Could you confirm whether when the user reloads the page WITHOUT sorting, it will decode and merge the array? Jun 27, 2016 at 17:16
  • Yes it can be done. Just call the function to get data. When the function doesn't find the data in sessions it will get it from the external source. And when it finds the data in sessions it will return the data from sessions only and you can perform whatever sorting you would like to.
    – Alok Patel
    Jun 27, 2016 at 17:52
  • So according to your requirement it won't execute multiple requests to external source.
    – Alok Patel
    Jun 27, 2016 at 17:53
  • So if(empty($data)) { Jun 27, 2016 at 20:56
  • 1
    Session variables should only be used for information relevant to the user, and/or needed by multiple disconnected components. it is VERY bad practice to use them as a data-dumping ground. Jun 29, 2016 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.