我正在从JSON读取一个多维数组。然后我需要根据两个参数进行排序,在数组中大约有3个级别。
我尝试过array_multisort,但一次只能做一个级别。然后我根据我在stackoverflow上看到的几个例子转移到了usort,但是它固执地拒绝工作。
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;
}
每个会议都有一个日期和时间 - 我需要按日期和时间排序,以填充会议日程页面。
我已经阅读了很多很多stackoverflow帖子。最有帮助的是 Sort multidimensional array by multiple criteria
Sort an associative array in php with multiple condition('order_by_date_time'函数的来源)
我已经在http://www.php.net/manual/en/function.usort.php(以及许多其他数组排序函数)上阅读了关于usort的PHP手册。
我还使用JSONLint验证了JSON,所以我不认为这是问题 - 但如果这可能是问题,我也可以改变它。
我知道之前已经提到了相关问题 - 我已经阅读了很多帖子,并尝试了很多建议的答案。但是,我的代码中缺少一些我无法看到的内容。
答案 0 :(得分:3)
这对你有用。
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");
答案 1 :(得分:0)
如何循环遍历所有会议,并添加额外的date_time
字段,这是两个字段的可排序组合。然后你只需要对那个进行排序。