简体   繁体   中英

PHP: Sort multi-dimensional 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));
    }
);

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)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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