我有一个json
文件,其中包含一个字段date
,该文件不是特定格式,应该保持这样。我想知道怎样才能用php对这个json进行排序,所以最近日期的记录会出现在json的开头,依此类推,直到结束时才按降序排列。
我尝试了很多东西,但没有什么对我有用。
这是json的样子:
[{"fullName":"John Doe","userName":"user2","phone":"+1234124512","email":"asd@bv.com","date":"2016-11-03","time":"1pm","reason":"some reason","isApproved":1,"label":"success","status":"Approved"},{"fullName":"Robert Royce","userName":"user1","phone":"+4460475640","email":"asd@asf.cv","date":"2016-11-17","time":"130pm","reason":"some reason","isApproved":1,"label":"success","status":"Approved"},{"fullName":"Pesho Zdr","userName":"user4","phone":"+4560477640","email":"grozdan@abv.bg","date":"2016-11-17","time":"130pm","reason":"some reason","isApproved":0,"label":"success","status":"Approved"}]
答案 0 :(得分:2)
$json = // your json here
$jsonArray = json_decode($json, true);
usort($jsonArray, function ($a, $b) {
return $a['date'] > $b['date'] ? -1 : 1;
});
$json = json_encode($jsonArray);
首先使用json_decode
$jsonArray = json_decode($json, true);
第二个参数用于指示输出需要是数组而不是对象
订购阵列;似乎usort
可以帮助你
usort($jsonArray, function ($a, $b) {
return $a['date'] > $b['date'] ? -1 : 1;
});
这将使数组从第一个值到最后一个值比较第一个($a
)和第二个($b
)。
特别是我们对date
价值感兴趣
要使usort
按预期工作,您需要从闭包返回一个值来告诉比较结果。
可能的结果是
最后,使用json_encode
$json = json_encode($jsonArray);