我试图按时间顺序排列这个数组:
$ta = array (
0 => '20/05/2012',
1 => '08/01/2011',
2 => '23/10/2010',
3 => '27/07/2013',
4 => '28/01/2011',
5 => '21/10/2010',
5 => '18/07/2013',
);
function comp2($a, $b) {
if ($a == $b)
return 0;
return ($a < $b) ? 1 : -1;
};
usort($ta,'comp2');
这将返回:
Array
(
[0] => 28/01/2011
[1] => 27/07/2013
[2] => 23/10/2010
[3] => 20/05/2012
[4] => 18/07/2013
[5] => 08/01/2011
)
在更改为 mm/dd/yyyy
后,我还使用 strtotime
转换了日期,但无济于事。
最佳答案
您可以简单地使用 usort
就像 as
usort($ta,function($a,$b){
return strtotime(str_replace('/', '-', $a)) - strtotime(str_replace('/', '-', $b));
});
简要说明:
这里的日期结构是美国日期格式,即m/d/Y
。因此需要首先替换为欧洲日期格式,即 d-m-y 。您可以查看this PHP 日期转换为 strtotime 的答案。
关于php - 为什么这个 usort 没有对日期数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32905238/