xar86413 xar86413 - 4 months ago 11
PHP Question

usort in PHP incorrect results

I have a list of game times, so say 1:05PM, 2:05PM, 7:10PM, 10:15PM etc. I am using a multidimensional array and

strcmp
with
usort
to sort these games in the correct order from earliest to latest.

The games are being sorted, however any game that starts at 10PM is being listed before any of the other games. So my current sort looks like this:

Dodgers 7/29/16 10:05 PM
Angels 7/29/16 10:10 PM
A's 7/29/16 10:15 PM
Cubs 7/29/16 2:20 PM
Jays 7/29/16 7:05PM
Rays 7/29/16 7:15PM
Astros 7/29/16 8:05 PM


etc

Ihave been troubleshooting this for days now. I tried to convert my date string using
strtotime()
, but usort doesn't like this at all and my sort becomes random. I have tried to format the date/time using hyphens instead of slashes, but nothing changes. I have 'scrubbed' my date/time string for any extra characters as well. Here is my code:

$array[$timedate] = $string;

// Multidimensional array of 'games'
$games[] = array('date' => $timedate,
'title' => $string);

// compare the dates and times
function cmp($a, $b)
{
return strcmp($a['date'], $b['date']);
}

// Sort the array
usort($games, "cmp");

Answer

Usort wants to define user-defined comparison function. You don't need that. Use clasic sort on strtotime().

Or you can use ksort, how you mentioned below. Here is the code, which works:

$game_times = array(array("Dodgers", "7/29/16 10:05 PM"), 
                    array("Angels", "7/29/16 10:10 PM"), 
                    array("A's", "7/29/16 10:15 PM"), 
                    array("Cubs", "7/29/16 2:20 PM"), 
                    array("Jays", "7/29/16 7:05PM"), 
                    array("Rays", "7/29/16 7:15PM"), 
                    array("Astros", "7/29/16 8:05 PM"));

foreach ($game_times as $item)
{
    $games[strtotime($item[1])] = array('date' => $item[1],
                                        'title' => $item[0]);
}

ksort($games);

var_dump($games);
Comments