【发布时间】:2013-08-02 20:41:05
【问题描述】:
我正在从 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,所以我认为这不是问题 - 但如果这可能是问题,我也可以更改它。
我知道以前在这里提出过相关问题 - 我已经阅读了很多帖子,并尝试了很多建议的答案。但是,我的代码中缺少一些我看不到的部分。
【问题讨论】: