John Davidson

Sorting JSON array from last to first by date in PHP, using a variable


thanks for taking the time to look at my question. I'm working on something that's dynamic and has data added daily, but is sorted from first to last in the JSON file, when I want to go from last (most recent) to first.

What I did was get the total number of entries by simply using

$total = $response['result']['total'];

Which gives me the total, 84. If I want the next last in the sequence, I just go:

 echo $total - 1

Which gives me 83.

This is where the problem comes in

I'm arranging my data like this:

echo $reo[0]['previous_day_doses_administered'];

Where the [0] is, I want $total - 1

However, I'm not sure how to get it, as it would be


which is definitely wrong. I'm wondering how to convert the $total to an integer, and have it no longer associated with the JSON array. I'm sorry if this is confusing! I just want to have the last 10 entries show up, instead of the first 10.

So, that's basically it. I've tried a couple things I found on here, but it screwed everything up. The API updates daily. If you want the link, let me know.

Thanks for taking the time to read this, and sorry that I'm being so confusing!

My Answer:
To sort the JSON array from last to first by date in PHP, you can use the following code snippet:

// Assuming $response is your JSON data
$response = json_decode($json, true);

// Sort the array by date in descending order
usort($response['result'], function($a, $b) {
return strtotime($b['date']) - strtotime($a['date']);

// Loop through the sorted array
foreach ($response['result'] as $data) {
echo $data['previous_day_doses_administered'] . "

This code snippet will sort the JSON array by date in descending order and then loop through the sorted array to display the data in the desired order. You can adjust the sorting logic based on your specific date format if needed.

Rate this post

3 of 5 based on 3099 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us