8

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 ( )
Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
Dave
  • 783
  • 3
  • 15
  • 25

1 Answers1

14

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);
}
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • 2
    http://www.php.net/manual/en/function.usort.php <-- example #2 uses a 2 dimensional array so our statement that he has to do it different bevause of the 2 dimensionality is wrong... – ITroubs Mar 21 '13 at 20:34
  • ITroubs is right, here is how to do it with usort: http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date – Miles M. Oct 14 '14 at 13:52