-1

I have an array of arrays. I want to order these arrays by their ['date'] field. So the latest is at index [0]. How can I do this?

Here is an example of my print_r

$array=    (
    [0] => Array
        (
            [date] => 01/05/2013 12:00
            [location] => Town Hall
            [minutes] => mydomain.com
            [agenda] => 
        ),
 [1] => Array
        (
            [date] => 09/05/2013 12:00
            [location] => Town Hall
            [minutes] => mydomain.com/walker
            [agenda] => 
        )

)
Claire
  • 3,383
  • 11
  • 41
  • 72

2 Answers2

1

just try this -

$array = array(
    0 => array('date'=>'01/05/2013 12:00', 'location'=>'A'),
    1 => array('date'=>'09/05/2013 12:00', 'location'=>'B'),
    2 => array('date'=>'03/05/2013 12:00', 'location'=>'C'),
    3 => array('date'=>'02/05/2013 12:00', 'location'=>'D')
);

echo '<pre>';
print_r($array);
echo '</pre>';

function sorting($a, $b){
    $a = strtotime($a['date']);
    $b = strtotime($b['date']);

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($array, "sorting");

echo '<pre>';
print_r($array);
echo '</pre>';

see live demo - http://codepad.org/biXJgHQA

HADI
  • 2,516
  • 1
  • 21
  • 24
  • Works like a charm, thank you. – Claire May 28 '13 at 08:52
  • :) my pleasure. You are most Nicola – HADI May 28 '13 at 08:56
  • Related question, would I be better storing it as a different format if I want to then check the first array date to see if it's in the future? – Claire May 28 '13 at 08:57
  • If you can sort it in first that will be better. Then you don't need to usort your array again. probably you are fetching your data from database. if so then write appropriate query for that. If not then you may need to use usort after getting full array – HADI May 28 '13 at 09:08
0

Try this:

usort($array,function($a,$b){
    return strcmp($a['date'],$b['date']);
}

or if PHP < 5.3

function my_sort($a,$b){
    return strcmp($a['date'],$b['date']);
}
usort($array,'my_sort');
StampyCode
  • 5,041
  • 2
  • 22
  • 40