在php中按降序显示json中数组的日期
我有一个JSON文件,其中有日期,但我想在它们通过foreach时按降序排序在php中按降序显示json中数组的日期,php,json,Php,Json,我有一个JSON文件,其中有日期,但我想在它们通过foreach时按降序排序 { "posts": [ { "id": "50", "name": "Charlotte Johnson", "date": "2021-02-08 10:15:38"
{
"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"
}
]
}
我循环浏览JSON文件中的数据。
我使用usort,但日期仍然没有显示递减
<?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 />";
}
?>
但我想按降序对它们进行排序,并像这样显示它们
Date: 2021-02-10 24:47:38
Date: 2021-02-09 18:30:38
Date: 2021-02-08 10:15:38
您能帮我查询一下吗?您需要反转函数参数
usort($datajson->posts, function($a, $b) {
return strtotime($b->date) - strtotime($a->date) ;
});
这是结果输出
对于降序,只需反转回调中的参数
$b-$a
。此外,这不是排序问题,但似乎不需要$date=date('Y-m-d H:i:s',strotime($row->date))代码>感谢你们两位指出问题所在。我已经从$date
中删除了该行。谢谢,我已经修改过了,它工作正常。
usort($datajson->posts, function($a, $b) {
return strtotime($b->date) - strtotime($a->date) ;
});