1

I have a JSON file, where there are dates, but I want to sort them in descending order when they go through a foreach.

{
    "posts": [
        {
            "id": "50",
            "name": "Charlotte Johnson",
            "date": "2021-02-08 10:15:38"
        },
        {
            "id": "51",
            "name": "Emma Jones",
            "date": "2021-02-09 18:30:38"
        },
        {
            "id": "52",
            "name": "Benjamin Miller",
            "date": "2021-02-10 23:47:38"
        }
    ]
}

I loop through the data from the JSON file. I use usort but the dates are still not showing descending.

<?php
    $datajson = json_decode(file_get_contents("results.json"));

    usort($datajson->posts, function($a, $b) {
       return strtotime($a->date) - strtotime($b->date);
    });

    foreach($datajson->posts as $row)
        {
            $date = date('Y-m-d H:i:s', strtotime($row->date));
            echo " Date: ". $date ."<br />";
        }
?>

the dates that the PHP shows me

Date: 2021-02-08 10:15:38
Date: 2021-02-09 18:30:38
Date: 2021-02-10 24:47:38

but I want to sort them in descending order and display them like this

Date: 2021-02-10 24:47:38
Date: 2021-02-09 18:30:38
Date: 2021-02-08 10:15:38

Can you help me with this query?

3
  • 3
    For descending, just reverse the parameters inside the callback $b - $a. Commented Feb 10, 2021 at 18:38
  • 1
    Also, not a sort issue, but this doesn't seem to be needed $date = date('Y-m-d H:i:s', strtotime($row->date)); Commented Feb 10, 2021 at 18:41
  • Thanks to both of you for indicate what the problem was. I already removed the line from the $ date. Commented Feb 10, 2021 at 19:05

1 Answer 1

1

You need to reverse the function parameters.

usort($datajson->posts, function($a, $b) {
         return strtotime($b->date) - strtotime($a->date) ;
     });

Here is result output

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I already modified and it worked.

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.