1

Hi I need to sort an array by date:

This is my array $get:

Array ( 
    [0] => Array ( 
        [Date] => 02.06.2012 
        [Theme] => test 
    ) 
    [1] => Array ( 
        [Date] => 03.07.2012 
        [Theme] => lol 
    ) 
    [2] => Array ( 
        [Date] => 09.06.2012 
        [Theme] => hm 
    ) 
) 

I tried following code:

function date_sort($a, $b) {
  return strcmp($a['Date'], $b['Date']);
}

usort($get, 'date_sort');

But all I get is unordered dates. My date is set dd.mm.yyyy!

1 Answer 1

2

Try doing

function date_sort($a, $b) {
    return strtotime($a['Date']) - strtotime($b['Date']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

strtotime() in a usort callback function? that's going to be sloooooow if you've got a lot of elements to sort. Better to run through the array first and populate an extra element with the converted date; then the sort will be much quicker.
also, be careful with strtotime() -- it makes assumptions about whether a date is dd mm yyyy or mm dd yyyy; read the manual page and make sure your dates aren't going to be converted incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.