Multidimensional PHP Sort Array by Date

I have a problem. I have a multidimensional array that looks like this:

Array ( [0] => 
              Array ( 
                    [0] => Testguy2 post. 
                    [1] => testguy2 
                    [2] => 2013-04-03 
              ) 

        [1] => Array ( 
                    [0] => Testguy post. 
                    [1] => testguy 
                    [2] => 2013-04-07 
              ) 
);

I want to sort messages from the newest date to the oldest date, so it looks like this:

Array ( [1] => Array ( 
                     [0] => Testguy post. 
                     [1] => testguy 
                     [2] => 2013-04-07 
               ) 
        [0] => Array ( 
                     [0] => Testguy2 post. 
                     [1] => testguy2 
                     [2] => 2013-04-03
               ) 
);

How to sort it?

+5
source share
4 answers
function cmp($a, $b){

    $a = strtotime($a[2]);
    $b = strtotime($b[2]);

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

usort($array, "cmp");
+4
source

You can do this using usortwith Closure:

usort($array, function($a, $b) {
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});
+4
source

I simply retreat from my desk during the day, so I cannot offer the specifics. But here is a good place to start, which includes examples: array_multisort

+2
source
$dates = array();       
foreach($a AS $val){
    $dates[] = strtotime($val[2]);
}
array_multisort($dates, SORT_ASC, $a);
+1
source

All Articles