2

I have array with a values like this

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

In fact these are dates. The problem is that I can`t figure out how to order them descending

1
  • is this your array key values???
    – jimy
    May 13, 2011 at 7:20

4 Answers 4

3

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

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.

1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.