IVAO CA-WM
IVAO CA-WM

Reputation: 73

Sort a 2d array by date (Y-m-d) date and time (Hi) columns

I am trying to sort a multidimensional array based on date/time, however it doesn't seem to be working correctly when I do a print_r. My best guess is that the time I provided to strtotime() is not in the correct format however the date and time formats are both listed, but separately in the php manual and no errors are thrown.

The format I use is unclear in the code so here it is: yyyy-mm-dd hhmm (24h with no colon GMT)

Here is the code:

function dateSort($a, $b){
    $d1 = strtotime($a['date'].' '.$a['startTime']);
    $d2 = strtotime($b['date'].' '.$a['startTime']);
    return $d1 - $d2;
}    
usort($events, 'dateSort');
print_r($events);

Upvotes: 0

Views: 664

Answers (2)

Toby D
Toby D

Reputation: 1421

From Php manual, you can try to update your dateSort() function

function dateSort($a, $b){
    $d1 = strtotime($a['date'].' '.$a['startTime']);
    $d2 = strtotime($b['date'].' '.$a['startTime']);
    return ($d1 < $d2) ? -1 : 1;
}    

Suggest you to give us some of your output, easier to take it from there.

Upvotes: 0

userlond
userlond

Reputation: 3828

IVAO. You had a typo in third line of snippet. Second line refers to $a, but in 3rd you mix both $b and $a :).

Also, I think, you needn't use strtotime at all. Look into snippet:

<?php

function dateSort($a, $b)
{
    $d1 = floatval(str_replace('-', '', $a['date']) . " $a[startTime]");
    $d2 = floatval(str_replace('-', '', $b['date']) . " $b[startTime]");
    return $d1 - $d2;
}

$events = [
    ['date' => '2015-05-01', 'startTime' => '2300', 'value' => 'Event 1'],
    ['date' => '2012-05-01', 'startTime' => '1430', 'value' => 'Event 2'],
    ['date' => '2011-09-17', 'startTime' => '1021', 'value' => 'Event 3'],
    ['date' => '2001-01-22', 'startTime' => '0959', 'value' => 'Event 4'],
    ['date' => '1999-02-05', 'startTime' => '1740', 'value' => 'Event 5'],
];

usort($events, 'dateSort');
echo '<pre>' . print_r($events, 1) . '</pre>';

And click to codepad.

Upvotes: 1

Related Questions