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?

$b - $a.$date = date('Y-m-d H:i:s', strtotime($row->date));$ date.