Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sort Array by date value [duplicate]

I have the following array format in my php code:

foreach ($events as $info) {
    $events_array[] = array(
        'title' => $info->Name,
        'date'  => $info->Date
    );
}
function cb($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}
usort($events_array, 'cb');

Edit: The date values are in the format: YYYY-MM-DD

Actually, when I do print_r, I get

[title] => SimpleXMLElement Object ( ) [date] => SimpleXMLElement Object ( )
like image 552
Dave Avatar asked Mar 21 '13 20:03

Dave


1 Answers

You have to create your own multi column sort function (because your array is 2-dimensional):

array_sort_by_column($events_array, 'date');

var_dump($events_array);

The sorting function:

function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();

    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}
like image 126
silkfire Avatar answered Oct 22 '22 20:10

silkfire