简体   繁体   English

如何在php中按日期对数组进行排序

[英]how can i sort array by date in php

I have this array and i want to sort it in ascending order by date. 我有这个数组,我想按日期升序排序。 I tried various answers from this site but none of them is working right. 我尝试了该站点的各种答案,但都无法正常工作。 So how can I do this? 那我该怎么做呢?

Array
(
    [0] => 09/01/2017
    [1] => 08/01/2017
    [2] => 07/01/2017
    [3] => 06/01/2017
    [4] => 05/01/2017
    [5] => 04/01/2017
    [6] => 03/01/2017
    [7] => 02/01/2017
    [8] => 01/01/2017
    [9] => 12/12/2016
    [10] => 11/12/2016
    [11] => 10/12/2016
    [12] => 09/12/2016
    [13] => 25/12/2016
    [14] => 24/12/2016
    [15] => 23/12/2016
    [16] => 26/12/2016
    [17] => 28/12/2016
    [18] => 30/12/2016
    [19] => 29/12/2016
    [20] => 22/12/2016
    [21] => 27/12/2016
    [22] => 15/12/2016
    [23] => 16/12/2016
    [24] => 14/12/2016
    [25] => 13/12/2016
    [26] => 17/12/2016
    [27] => 18/12/2016
    [28] => 20/12/2016
    [29] => 19/12/2016
    [30] => 21/12/2016
)

I am using PHP. 我正在使用PHP。 This is what i tried so far. 这是我到目前为止尝试过的。 This function doesn't sort as mentioned in all other questions. 此功能未按其他所有问题所述进行排序。

$data = array listed above;
function cmp($a, $b)
{
    if (strtotime($a) == strtotime($b))
    {
        return 0;
    }
    return (strtotime($a) < strtotime($b)) ? -1 : 1;
}

uasort($data, "cmp");

For you string is dd/mm/yy type, cannot directly used by strtotime or date_create . 因为您的字符串是dd/mm/yy类型,所以不能被strtotimedate_create直接使用。 You can use DataTime to create the datetime , then use the datetime compare operators. 您可以使用DataTime创建datetime ,然后使用datetime比较运算符。

usort($array, function($a, $b){return DateTime::createFromFormat('d/m/Y', $a) > DateTime::createFromFormat('d/m/Y', $b);});
$document_list = array( array );
$document_list= array_map(function($v) {
    return date('Y-m-d', strtotime($v));
}, $document_list);

function sortByDate($a, $b) {
    return  strtotime($b) - strtotime($a);
}

usort($document_list, "sortByDate");

$document_list= array_map(function($v) {
    return date('m-d-Y', strtotime($v));
}, $document_list);
function desc_date_sort($a, $b){
    $date1ts = DateTime::createFromFormat('d/m/Y', $a);
    $date2ts = DateTime::createFromFormat('d/m/Y', $b);
    return $date1ts === $date2ts ? 0 : ( $date1ts < $date2ts ? 1 : -1 ); 
}
usort($dates_array, 'desc_date_sort');
function cmp($a,$b){
    return strtotime($a['created'])<strtotime($b['created'])?1:-1;
};
// $array pass your array name
uasort($array,'cmp');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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