简体   繁体   中英

How sort date in array form oldest to newest php

I have a problem. I can't sort date in array from oldest to newest ;/ My array:

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

i want output

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',
)

i use own function callback in usort, but this not work ;/

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

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

someone has an idea for a solution?

The best sort is:

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;
        });

First, I remove all the zero values from the array, then sort it as needed, and then add zero values back:

$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);

This sorts your array as following:

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
)

This will give the result you want tested in PHP versions 5.3.22 - 5.6.18, but there has been changes in PHP 7 that affect the usort function:

$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;
});

Output:

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
)

Test:

https://3v4l.org/0Tvlm

You have the date comparison backwards. You have:

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

You want:

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

You can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM