以下是我的数组的内容:
array(
'June 01, 2014' => array(
(int) 722107 => array(
'date' => 'June 01, 2014',
'start_time' => '2:00 AM',
'end_time' => '03:00 AM'
),
(int) 117646 => array(
'date' => 'June 01, 2014',
'start_time' => '12:30 AM',
'end_time' => '03:30 AM'
)
),
'May 31, 2014' => array(
(int) 769349 => array(
'date' => 'May 31, 2014',
'start_time' => '12:30 AM',
'end_time' => '03:30 AM'
)
)
)
我想要的输出是它应该首先按键排序(ASC中的日期),然后再按ASC中的开始时间排序每个键的值。
根据上面的例子,它应输出:
array(
'May 31, 2014' => array(
(int) 769349 => array(
'date' => 'May 31, 2014',
'start_time' => '12:30 AM',
'end_time' => '03:30 AM'
)
),
'June 01, 2014' => array(
(int) 117646 => array(
'date' => 'June 01, 2014',
'start_time' => '12:30 AM',
'end_time' => '03:30 AM'
),
(int) 722107 => array(
'date' => 'June 01, 2014',
'start_time' => '2:00 AM',
'end_time' => '03:00 AM'
)
)
)
答案 0 :(得分:5)
两次传递可以与uksort()
和uasort()
一起使用自定义函数来比较两个日期:
function timeCompare($a, $b)
{
$va = strtotime($a);
$vb = strtotime($b);
if ($va != $vb) {
return $va < $vb ? -1 : 1;
}
return 0;
}
// first pass (sort outer elements)
uksort($data, 'timeCompare');
// second pass (sort inner elements)
foreach ($data as &$item) {
uasort($item, function($a, $b) {
return timeCompare($a['start_time'], $b['start_time']);
});
}
答案 1 :(得分:2)
这将按照您的要求对其进行排序。
$sort = array();
foreach ($d as $key => $item) {
$sort[$key] = strtotime($key);
}
array_multisort($sort, SORT_ASC, $d);
function sortme($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
}
foreach ($d as $k => $i) {
usort($i, "sortme");
}
返回:
Array
(
[May 31, 2014] => Array
(
[769349] => Array
(
[date] => May 31, 2014
[start_time] => 12:30 AM
[end_time] => 03:30 AM
)
)
[June 01, 2014] => Array
(
[722107] => Array
(
[date] => June 01, 2014
[start_time] => 2:00 AM
[end_time] => 03:00 AM
)
[117646] => Array
(
[date] => June 01, 2014
[start_time] => 12:30 AM
[end_time] => 03:30 AM
)
)
)
May 31, 2014/ June 01, 2014/ ETC
进行排序。foreach
循环,通过子数组对它们进行日期/时间排序。