用多个条件对PHP中的多维数组进行排序 [英] Sorting multi-dimensional array in PHP with multiple criteria
问题描述
我正在从JSON读取多维数组.然后,我需要根据两个参数进行排序,大约在数组的3个层次中.
I'm reading a multi-dimensional array from JSON. I then need to sort based on two of the parameters, about 3 levels deep in the array.
我尝试过array_multisort,但是一次只能做一个级别.然后我根据在stackoverflow上看到的几个示例转移到了usort,但是它顽固地拒绝了工作.
I've tried array_multisort, but could only do one level at a time. I then moved to usort, based on several examples I saw here on stackoverflow, but it stubbornly refuses to work.
JSON:
[
{
"multiple parameters": "foobar",
"projects": [
{
"id": "00101",
"date": "9",
"time": "14:00",
"duration":"30"
},
{
"id": "EX001",
"date": "8",
"time": "13:30",
"duration":"15"
},
{
"id": "9A200",
"date": "10",
"time": "8:45",
"duration":"15"
},
{
"id": "EQ002",
"date": "8",
"time": "9:30",
"duration":"15"
}
]
}
]
PHP:
//read data from the json file
$theschedule = '/directory/path/schedule.json';
//read json file
if (file_exists ($theschedule)){
$contents = utf8_encode(file_get_contents($theschedule));
$Schedule= json_decode($contents, true);
//Sort array
usort($Schedule[0]['projects'], 'order_by_date_time');
function order_by_date_time($a, $b)
{
if ($a['date'] == $b['date'])
{
// date is the same, sort by time
if ($a['time'] == $b['time']) return 0;
return $a['time'] == 'y' ? -1 : 1;
}
// sort the date first:
return $a['date'] < $b['date'] ? 1 : -1;
}
每个会议都有一个日期和时间-我需要先按日期排序,然后再按时间填充会议时间表页面.
Each meeting has a date and time - I need to sort by date, and then time, to populate a meeting schedule page.
我读了很多很多关于stackoverflow的文章.最有帮助的是 按多个条件对多维数组进行排序
I've read many, many stackoverflow posts. The most helpful were Sort multidimensional array by multiple criteria
在具有多个条件的php中对关联数组进行排序("order_by_date_time"功能的来源)
Sort an associative array in php with multiple condition (source of the 'order_by_date_time' function)
我已经在 http://www上阅读了有关usort的PHP手册. .php.net/manual/en/function.usort.php (以及许多其他数组排序函数).
I've read the PHP manual on usort at http://www.php.net/manual/en/function.usort.php (and many of the other array sort functions).
我还使用JSONLint验证了JSON,所以我认为这不是问题-但是,如果这可能是问题,我也可以对其进行更改.
I've also validated the JSON with JSONLint, so I don't think it's the problem - but if that might be the problem, I can change it as well.
我知道以前在这里提出过相关问题-我已经阅读了很多帖子,并尝试了很多建议的答案.但是,我的代码中却缺少一些我看不见的东西.
I know related questions have been raised here before - I've read so many of the posts, and tried so many of the suggested answers. There's some piece missing in my code, though, that I just can't see.
推荐答案
这应该对您有用.
function order_by_date_time($a, $b){
if ($a["date"] == $b["date"]){
return strtotime($a["time"]) - strtotime($b["time"]);
}
return $a["date"] - $b["date"];
}
usort ($Schedule[0]['projects'], "order_by_date_time");
这篇关于用多个条件对PHP中的多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!