簡體   English   中英

如何以最早到最新的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;
        });

首先,我從數組中刪除所有零值,然后根據需要對其進行排序,然后再添加零值:

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

這將提供您想要在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

您將日期比較向后。 你有:

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

你要:

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

您可以使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM