1

Possible Duplicate:
Sorting an associative array in PHP

I have this array

array
  0 => 
    array
      'start_date' => string '2012-11-14' (length=10)
      'end_date' => string '2012-11-19' (length=10)
  1 => 
    array
      'start_date' => string '1980-10-10' (length=10)
      'end_date' => string '1980-10-10' (length=10)
  2 => 
    array
      'start_date' => string '2012-11-20' (length=10)
      'end_date' => string '2099-10-10' (length=10)

I want to sort it on start_date. I dont think sort() method works on it. Any idea?

1

2 Answers 2

2

You can use usort :

PHP 5.3+

usort($array, function($a, $b) {
   //return strtotime($a['start_date']) - strtotime($b['start_date']);
   return strcmp($a['start_date'], $b['start_date']);
});

Older versions of PHP

function startDateCmp($a, $b) {
   //return strtotime($a['start_date']) - strtotime($b['start_date']);
   return strcmp($a['start_date']), $b['start_date']);
}

usort($array, 'startDateCmp');
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, anonymous functions was introduced with php 5.3
in this particular case, strtotime is overkill. the dates are already in a string format that can be sorted directly. but otherwise yes, you'd have to convert to a timestamp before comparing.
@MarcB, I like to play safe, but you're right :)
@MarcB Assuming certain dates are formatted "2012-05-01" and not "2012-5-1", you're right.
1

Use usort and supply your own function to do the ordering.

function cmp($a, $b)
{
    return $b['start_date'], $a['start_date'];
}

usort($array, "cmp");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.