开发者

Order array with dates

I have array with a values like this

04|2012
05|2011
05|2011
06|2011
08|2011

In fa开发者_JS百科ct these are dates. The problem is that I can`t figure out how to order them descending


Assuming that that format represents month|year and you're running PHP 5.3+:

usort($array, function ($a, $b) {
    $toTime = function ($str) {
        list($month, $year) = explode('|', $str);
        return mktime(0, 0, 0, $month, 1, $year);
    }

    $a = $toTime($a);
    $b = $toTime($b);

    if ($a == $b) {
        return 0;
    }
    return $a < $b ? -1 : 1;
});


If you use SQL-like date format (yyyy-mm-dd) then you may sort dates directly as strings in any order.

If date format can't change:

<?php

$a = array(
    '04|2012',
    '05|2011',
    '05|2011',
    '06|2011',
    '08|2011',
);


function compare_strange_dates($date1, $date2) {
    return strcmp(
        implode('-', array_reverse(explode('|', $date1))),
        implode('-', array_reverse(explode('|', $date2)))
    );
}

usort($a, 'compare_strange_dates'); // ascending
$d = array_reverse($a); // descending

var_dump($a);
var_dump($d);

If you want only descending order, swap $date1 and $date2 in compare_strange_dates() return statement and use only usort.


With $dates being your array, you can do (demo)

usort($dates, function($a, $b) {
    return DateTime::createFromFormat('m\|Y', $b)->format('U')
         - DateTime::createFromFormat('m\|Y', $a)->format('U');
});
print_r($dates);

An alternative that doesnt require converting to dates and should be quicker, would be (demo)

usort($dates, function($a, $b) {
    return preg_replace('#(\d{2})\|(\d{4})#', '$2$1', $b)
         - preg_replace('#(\d{2})\|(\d{4})#', '$2$1', $a);
});
print_r($dates);

Both output

Array
(
    [0] => 04|2012
    [1] => 08|2011
    [2] => 06|2011
    [3] => 05|2011
    [4] => 05|2011
)

Note: all of these require PHP 5.3+ due to the lambdas.


If you need to sort using only this 2 items from the array, you can concatenate year and days in a single item in a one dimension array of integers and having something like:

201204
201105
201105
201106
201108

and after this sort it like an ussual one dimensional array, but in descending order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜