Sorting an array of times

If I have an array like so…

$arrTimes = array(
   0 => array('time' => '1:00', 'notation' => 'am'),
   1 => array('time' => '10:10', 'notation' => 'pm'),
   2 => array('time' => '2:30', 'notation' => 'pm'),
   3 => array('time' => '1:00', 'notation' => 'pm'),
   4 => array('time' => '8:15', 'notation' => 'am'),
   5 => array('time' => '11:20', 'notation' => 'am')
);

…and I want to output a string in order of earliest to latest times…

$strTimes = '1:00 am, 11:20 am, 1:00 pm, 2:30 pm, 10:10 pm';

…would this be a good way to go about it?

usort($arrTimes, create_function('$a, $b', 'return strnatcmp($b["time"], $a["time"]);'));
usort($arrTimes, create_function('$a, $b', 'return strnatcmp($a["notation"], $b["notation"]);'));

foreach($arrTimes as $arrTime){
	$strTimes .= $arrTime['time'] . ' ' . $arrTime['notation'] . ', ';	
}

$strTimes = rtrim($strTimes, ', ');

I couldn’t get this to work until I switched the order of comparison variables in the first usort() and I’m not sure if I’ve somehow quirked my way into the desired result.

Here’s how I would do it. :slight_smile:


<?php
$arrTimes = array(
   0 => array('time' => '1:00', 'notation' => 'am'),
   1 => array('time' => '10:10', 'notation' => 'pm'),
   2 => array('time' => '2:30', 'notation' => 'pm'),
   3 => array('time' => '1:00', 'notation' => 'pm'),
   4 => array('time' => '8:15', 'notation' => 'am'),
   5 => array('time' => '11:20', 'notation' => 'am')
);

function sortByTime($a, $b){
  $a = strtotime($a['time'] . $a['notation']);
  $b = strtotime($b['time'] . $b['notation']);
  return $a - $b;
}

usort($arrTimes, 'sortByTime');

var_dump(
  $arrTimes
);

/*
  array(6) {
    [0]=>
    array(2) {
      ["time"]=>
      string(4) "1:00"
      ["notation"]=>
      string(2) "am"
    }
    [1]=>
    array(2) {
      ["time"]=>
      string(4) "8:15"
      ["notation"]=>
      string(2) "am"
    }
    [2]=>
    array(2) {
      ["time"]=>
      string(5) "11:20"
      ["notation"]=>
      string(2) "am"
    }
    [3]=>
    array(2) {
      ["time"]=>
      string(4) "1:00"
      ["notation"]=>
      string(2) "pm"
    }
    [4]=>
    array(2) {
      ["time"]=>
      string(4) "2:30"
      ["notation"]=>
      string(2) "pm"
    }
    [5]=>
    array(2) {
      ["time"]=>
      string(5) "10:10"
      ["notation"]=>
      string(2) "pm"
    }
  }
*/

Thanks Anthony, that looks a lot nicer :smiley: