数组中的日期如何从最旧到最新的 php 进行排序


How sort date in array form oldest to newest php

>我有一个问题。我无法从最旧到最新的数组中对日期进行排序;/我的阵列:

$arr = array('2013-02-01','2000-02-01','2016-02-17','0000-00-00','0000-00-00','0000-00-00');

我想要输出

array(
[0] => '2000-02-01',
[1] => '2013-02-01',
[2] => '2016-02-01',
[3] => '0000-00-00',
[4] => '0000-00-00',
[5] => '0000-00-00',
)

我在 usort 中使用自己的函数回调,但这不起作用;/

function sortDate($a, $b)
{
    if ($a == $b) {
        return 0;
    } elseif($a == '0000-00-00') {
        return 1;
    }
    return strtotime($a) < strtotime($b) ? 1 : -1;
}

有人有解决方案的想法吗?

最好的排序是:

usort($childs, function ($a, $b) {
            if ($a == '0000-00-00')
                return 1;
            if ($b == '0000-00-00')
                return -1;
            if ($a == $b)
                return 0;
            return ($a < $b) ? -1 : 1;
        });

这将给出你想要在 PHP 版本 5.3.22 - 5.6.18 中测试的结果,但 PHP 7 中有一些更改影响了 usort 函数:

$arr = array('2013-02-01','2000-02-01','2016-02-17','0000-00-00','0000-00-00','0000-00-00');
sort( $arr );
usort( $arr, function( $a, $b )
{
    if ( $a === $b ) return 0;
    if ( strpos( $b, '0000' ) !== false ) return -1;
    return ( $a < $b ) ? -1 : 1;
});

输出:

Array
(
    [0] => 2000-02-01
    [1] => 2013-02-01
    [2] => 2016-02-17
    [3] => 0000-00-00
    [4] => 0000-00-00
    [5] => 0000-00-00
)

测试:

https://3v4l.org/0Tvlm

首先,我从数组中删除所有零值,然后根据需要对其进行排序,然后重新添加零值:

$arr = array('2013-02-01','2000-02-01','2016-02-17','0000-00-00','0000-00-00','0000-00-00');
$count = count($arr);
$arr = array_filter($arr, function($v) {
    if($v == '0000-00-00') {
        return false;
    } else {
        return true;
    }
}, ARRAY_FILTER_USE_BOTH);
$count -= count($arr);
sort($arr);
$arr = array_merge($arr, array_fill(0, $count, '0000-00-00'));
print_r($arr);

这会按如下方式对数组进行排序:

Array
(
    [0] => 2000-02-01
    [1] => 2013-02-01
    [2] => 2016-02-17
    [3] => 0000-00-00
    [4] => 0000-00-00
    [5] => 0000-00-00
)

你有日期比较倒过来。你有:

return strtotime($a) < strtotime($b) ? 1 : -1;

你想要:

return strtotime($a) < strtotime($b) ? -1 : 1;

您可以使用:

return $a < $b ? -1 : 1;