Wednesday, 29 August 2018

PHP: Sorting a multidimensional array by date

I 've got an array that looks like this:

Array (
       [0] =>
          Array (
                   [2014-05-31] => value1
                ) 

       [1] =>
          Array (
                   [2014-04-17] => value2
                ) 

       [2] =>
         Array (
                   [2014-04-21] => value3
               )
    )

....etc....
I'd like to sort this whole array by date starting from highest to lowest (or lowest to highest - it's not important which). I've looked into ksort but I could only get it to sort the array based on the index ( [0], [1], [2]) which it is already in the right order. What i'd like is something like this:
Array (
       [1] =>
          Array (
                   [2014-04-17] => value2
                ) 

       [2] =>
         Array (
                   [2014-04-21] => value3
               )

       [0] =>
          Array (
                   [2014-05-31] => value1
                ) 

    )

In the above example we've sorted it from earliest date to the latest. How can I achieve this?

usort(
    $array,
    function($a, $b) {
        return strcmp(key($a), key($b));
    }
);

0 comments:

Post a Comment