Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort multidimensional array by date

I'm having a problem. I have a multidimensional array, that looks like this:

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

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

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

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

How do I sort it?

like image 566
user1845954 Avatar asked Apr 07 '13 15:04

user1845954


People also ask

How do I sort a multidimensional array in PHP?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

How does Usort work in PHP?

The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.


2 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");

Or for >= PHP 7

usort($array, function($a, $b){
    return strtotime($a[2]) <=> strtotime($b[2]);
});
like image 192
472084 Avatar answered Oct 12 '22 23:10

472084


You can do it using usort with a Closure :

usort($array, function($a, $b) {
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});
like image 42
Alain Tiemblo Avatar answered Oct 12 '22 23:10

Alain Tiemblo