0

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?

2
  • Wait... if your arrays contain several dates you cannot sort the main array ? Example: [1] => [ [2014-04-17] => value2, [2013-04-17] => value4] ], [2] => [ [2014-04-21] => value3 ] Commented Apr 13, 2014 at 12:46
  • No - there's only one date per level. Commented Apr 13, 2014 at 12:54

2 Answers 2

5
usort(
    $array,
    function($a, $b) {
        return strcmp(key($a), key($b));
    }
);
Sign up to request clarification or add additional context in comments.

1 Comment

array_pop(array_flip($x)) could simply be key($x) but this is the better answer - the nature of the date format lends itself to string comparison - there's no need to parse the timestamp.
1

You can use usort for a user-defined comparision.
Try this -

$arr = Array (
          Array( 
                   "2014-05-31" => "value1"
                ),
          Array ( 
                   "2014-04-17" => "value2"
                ),
         Array ( 
                   "2014-04-21" => "value 3"
               )
    );
$res = usort($arr, function($a, $b){
    $par1 = key($a);
    $par2 = key($b);
    if ($par1 == $par2) {
        return 0;
    }
    return ($par1 < $par2) ? -1 : 1;
});
var_dump($arr);
/*
    OUTPUT
    array
      0 => 
        array
          '2014-04-17' => string 'value2' (length=6)
      1 => 
        array
          '2014-04-21' => string 'value 3' (length=7)
      2 => 
        array
          '2014-05-31' => string 'value1' (length=6)
*/

1 Comment

Is this for PHP >5.3 only? Could this be rewritten to work for below 5.3?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.