phparrayssortingdatetimemultidimensional-array

Sort a 2d array by a datetime column formatted as Y-m-d H:i:s


Here is my array:

Array ( 
    [0] => Array ( [0] => content here [1] => 2010-02-04 01:25:34 )
    [1] => Array ( [0] => content here [1] => 2010-02-04 04:51:37 ) 
    [2] => Array ( [0] => content here [1] => 2010-02-04 04:52:31 ) 
    [3] => Array ( [0] => content here [1] => 2010-02-04 05:50:48 ) 
    [4] => Array ( [0] => content here [1] => 2010-02-04 03:25:34 ) 
    [5] => Array ( [0] => content here [1] => 2010-02-04 05:39:33 ) 
    [6] => Array ( [0] => content here [1] => 2010-02-04 03:25:34 ) 
    [7] => Array ( [0] => content here [1] => 2010-02-04 07:07:09 ) 
    [8] => Array ( [0] => content here [1] => 2010-02-04 07:07:23 ) 
    [9] => Array ( [0] => content here [1] => 2010-02-04 08:51:18 ) 
) 

How can I sort it by the timestamp?


Solution

  • Or usort() with strtotime():

    function compare($e1, $e2) {
        $t1 = strtotime($e1[1]));
        $t2 = strtotime($e2[1]));
    
        if($t1 == t2) {
           return 0;
        }
        return ($t1 > $t2) ? 1 : -1;
    }
    
    
    usort($array, 'compare');