我有一个像这样的数组,我想按日期排序这个数组如何排序这个数组
Array
(
[0] => 28/02/2016
[1] => 30/01/2016
[2] => 16/02/2016
[3] => 19/02/2016
[4] => 24/02/2016
[5] => 13/02/2016
[6] => 18/02/2016
[7] => 27/02/2016
[8] => 25/02/2016
[9] => 01/02/2016
[10] => 02/02/2016
[11] => 03/02/2016
[12] => 05/02/2016
[13] => 06/02/2016
[14] => 07/02/2016
[15] => 08/02/2016
[16] => 11/02/2016
[17] => 12/02/2016
)
我使用了 usort 但它不起作用,我正在编写一个函数并将其转换为 strtotime 但它不起作用。
尝试以下解决方案:
$array = array
(
0 => '28/02/2016',
1 => '30/01/2016',
2 => '16/02/2016',
3 => '19/02/2016',
4 => '24/02/2016',
5 => '13/02/2016',
6 => '18/02/2016',
7 => '27/02/2016',
8 => '25/02/2016',
9 => '01/02/2016',
10 => '02/02/2016',
11 => '03/02/2016',
12 => '05/02/2016',
13 => '06/02/2016',
14 => '07/02/2016',
15 => '08/02/2016',
16 => '11/02/2016',
17 => '12/02/2016'
);
function sortFunction( $a, $b ) {
$date1 = DateTime::createFromFormat('d/m/Y', $a);
$date2 = DateTime::createFromFormat('d/m/Y', $b);
return $date1->getTimestamp() - $date2->getTimestamp();
}
usort($array, "sortFunction");
print_r($array);
输出
Array
(
[0] => 30/01/2016
[1] => 01/02/2016
[2] => 02/02/2016
[3] => 03/02/2016
[4] => 05/02/2016
[5] => 06/02/2016
[6] => 07/02/2016
[7] => 08/02/2016
[8] => 11/02/2016
[9] => 12/02/2016
[10] => 13/02/2016
[11] => 16/02/2016
[12] => 18/02/2016
[13] => 19/02/2016
[14] => 24/02/2016
[15] => 25/02/2016
[16] => 27/02/2016
[17] => 28/02/2016
)
使用 sort() 尝试一下
$array = array
(
0 => '28/02/2016',
1 => '30/01/2016',
2 => '16/02/2016',
3 => '19/02/2016',
4 => '24/02/2016',
5 => '13/02/2016',
6 => '18/02/2016',
7 => '27/02/2016',
8 => '25/02/2016',
9 => '01/02/2016',
10 => '02/02/2016',
11 => '03/02/2016',
12 => '05/02/2016',
13 => '06/02/2016',
14 => '07/02/2016',
15 => '08/02/2016',
16 => '11/02/2016',
17 => '12/02/2016'
);
foreach($array as $key=>$val) {
$date_arr=explode('/',$val);
$time_arr[$key]=strtotime($date_arr[2].'/'.$date_arr[1].'/'.$date_arr[0]);
}
sort($time_arr);
foreach($time_arr as $key=>$val) {
$array[$key]=date("d/m/Y", $val);
}
echo '<pre>'; print_r($array); echo '</pre>';
输出
Array
(
[0] => 30/01/2016
[1] => 01/02/2016
[2] => 02/02/2016
[3] => 03/02/2016
[4] => 05/02/2016
[5] => 06/02/2016
[6] => 07/02/2016
[7] => 08/02/2016
[8] => 11/02/2016
[9] => 12/02/2016
[10] => 13/02/2016
[11] => 16/02/2016
[12] => 18/02/2016
[13] => 19/02/2016
[14] => 24/02/2016
[15] => 25/02/2016
[16] => 27/02/2016
[17] => 28/02/2016
)