Alex
Alex

Reputation: 6645

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?

Upvotes: 1

Views: 199

Answers (5)

Quasipickle
Quasipickle

Reputation: 4498

array_multisort() It's a nasty but powerful little function. Basically you'll have to iterate through your array, pulling out the date stamp into a new array - maintaining key association. Then, sort that new array, still maintaining key association. Then throw both your newly sorted array and the original array into array_multisort() and your original array will be sorted to have keys in the same order as your sorted array.

Clear as mud? The examples on that doc page should help.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816262

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');

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

Use usort() with a cmp_function that compares index 1 of each of the passed arguments.

Upvotes: 1

Luca Matteis
Luca Matteis

Reputation: 29267

How about Bubble sort?

That means looping through each date, check if the previous is bigger, etc.

Upvotes: -1

Sarfraz
Sarfraz

Reputation: 382616

Use array_multisort.

Upvotes: 0

Related Questions