我想在不丢失密钥的情况下对数组进行排序。我在stackoverflow上阅读了许多类似的问题,但没有一个处理日期作为密钥。希望有人可以帮助我!
这是我想要排序的数组。
$data = array (
'October 8, 2015' =>
array (
'admin' =>
array (
'checkin' => 1,
'checkout' => 0,
),
),
'September 8, 2015' =>
array (
'admin' =>
array (
'checkin' => 1,
'checkout' => 0,
),
),
'September 7, 2015' =>
array (
'admin' =>
array (
'checkin' => 1,
'checkout' => 1,
),
),
'September 6, 2015' =>
array (
'admin' =>
array (
'checkin' => 2,
'checkout' => 2,
),
),
'September 5, 2015' =>
array (
'admin' =>
array (
'checkin' => 1,
'checkout' => 1,
),
),
'September 4, 2015' =>
array (
'admin' =>
array (
'checkin' => 1,
'checkout' => 1,
),
),
'September 3, 2015' =>
array (
'admin' =>
array (
'checkin' => 2,
'checkout' => 2,
),
),
'September 2, 2015' =>
array (
'admin' =>
array (
'checkin' => 2,
'checkout' => 1,
),
),
);
答案 0 :(得分:1)
使用uksort。你可以自己做比较功能。在那里你可以将密钥转换为时间戳并进行比较。
您可以更改订单方向
return $a > $b; // order ASC
return $a < $b; // order DESC
您的代码应如下所示:
function cmp($a, $b)
{
$a = strtotime($a);
$b = strtotime($b);
return $a > $b;
}
uksort($data, "cmp");
参见 DEMO
<强>输出强>
Array
(
[September 2, 2015] => Array
(
[admin] => Array
(
[checkin] => 2
[checkout] => 1
)
)
[September 3, 2015] => Array
(
[admin] => Array
(
[checkin] => 2
[checkout] => 2
)
)
[September 4, 2015] => Array
(
[admin] => Array
(
[checkin] => 1
[checkout] => 1
)
)
[September 5, 2015] => Array
(
[admin] => Array
(
[checkin] => 1
[checkout] => 1
)
)
[September 6, 2015] => Array
(
[admin] => Array
(
[checkin] => 2
[checkout] => 2
)
)
[September 7, 2015] => Array
(
[admin] => Array
(
[checkin] => 1
[checkout] => 1
)
)
[September 8, 2015] => Array
(
[admin] => Array
(
[checkin] => 1
[checkout] => 0
)
)
[October 8, 2015] => Array
(
[admin] => Array
(
[checkin] => 1
[checkout] => 0
)
)
)