[英]Sort Month-Year multidimensional array in PHP using uksort
I want to sort the following array: 我想对以下数组进行排序:
Array(
[05/2017] => Array (
[city] => 'ABC'
[memebers] => '50'
)
[03/2017] => Array (
[city] => 'ABC'
[members] => '25'
)
[10/2016] => Array (
[city] => 'ABC'
[members] => '20'
)
[11/2017] => Array (
[city] => 'ABC'
[members] => '65'
)
)
The expected result: 预期结果:
Array(
[10/2016] => Array (
[city] => 'ABC'
[members] => '20'
)
[03/2017] => Array (
[city] => 'ABC'
[members] => '25'
)
[05/2017] => Array (
[city] => 'ABC'
[members] => '50'
)
[11/2017] => Array (
[city] => 'ABC'
[members] => '65'
)
)
I'm using uksort
to sort it, but I guess uksort
does not work with multidimensional array: 我正在使用
uksort
进行排序,但是我想uksort
不适用于多维数组:
uksort($data, function($a1, $a2) {
$time1 = strtotime($a1);
$time2 = strtotime($a2);
return $time1 - $time2;
});
Please suggest how will it work with uksort
or any other possibility? 请提出如何与
uksort
或其他任何可能性一起使用?
This should works : 这应该工作:
$data =
array(
'05/2017' => array (
'city' => 'ABC',
'memebers' => '50'
),
'03/2017' => array (
'city' => 'ABC',
'members' => '25'
),
'10/2016' => array (
'city' => 'ABC',
'members' => '20'
),
'11/2017' => array (
'city' => 'ABC',
'members' => '65'
),
);
uksort($data, function($a1, $a2) {
return DateTime::createFromFormat('m/Y|', $a1) <=> DateTime::createFromFormat('m/Y|', $a2);
});
var_dump($data);
You need to use DateTime since your dates are not well formated, then just compare the timestamps. 由于日期的格式不正确,因此需要使用DateTime,然后只需比较时间戳即可。 As pointed by Mark, use "m" for months, and you can use "<=>" operator (since PHP 7)
正如Mark所指出的,请使用“ m”数月,然后可以使用“ <=>”运算符(自PHP 7起)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.