我有一个键为“ Y-m”格式的数组。我想根据此键对该数组进行排序。
$array = array(
"2018-10" => 239,
"2018-11" => 264,
"2018-12" => 237,
"2019-01" => 211,
"2019-04" => "0",
"2019-03" => "0",
"2019-02" => "0"
);
我的最终结果应该是:
$array = array(
"2019-04" => "0",
"2019-03" => "0",
"2019-02" => "0",
"2019-01" => 211,
"2018-12" => 237,
"2018-11" => 264,
"2018-10" => 239
);
这是到目前为止我尝试过的代码。
$sorter = function($a, $b) {
if (strtotime($a) == strtotime($b)) {
return 0;
}
return (strtotime($a) < strtotime($b)) ? -1 : 1;
};
uksort($array, $sorter);
答案 0 :(得分:3)
我认为您可以使用krsort()php函数执行类似的操作
$array = array(
"2018-10" => 239,
"2018-11" => 264,
"2018-12" => 237,
"2019-01" => 211,
"2019-04" => "0",
"2019-03" => "0",
"2019-02" => "0"
);
krsort($array);
工作示例:-https://3v4l.org/LqKa6
答案 1 :(得分:1)
<?php
$array = array(
"2018-10" => 239,
"2018-11" => 264,
"2018-12" => 237,
"2019-01" => 211,
"2019-04" => "0",
"2019-03" => "0",
"2019-02" => "0"
);
$date_keys = array_keys($array);
usort($date_keys,function($date1,$date2){
$date_1 = new DateTime($date1);
$date_2 = new DateTime($date2);
if($date_1 > $date_2) return -1;
else if($date_1 < $date_2) return 1;
return 0;
});
$rearranged_data = [];
foreach($date_keys as $each_key){
$rearranged_data[$each_key] = $array[$each_key];
}
$array = $rearranged_data;
print_r($array);
答案 2 :(得分:1)
ksort()
函数根据键对关联数组进行升序排序。
答案 3 :(得分:-1)
尝试一下。
$array = array();
foreach($sortedArray AS $key => $value){
$key = date('Y-m-d',strtotime($key));
$array[$key] = $value;
}
// sort the new array on keys in reverse
ksort($array);