I have a non-associative array where the data that comes in is not sorted (I\'m receiving the data from an outside system and cannot force it to come into the array in sorte
Sensibly sorting on time (chronologically) will call for strtotime()
.
Here is a one-liner for you using array_multisort()
. array_map()
and strtotime()
are called to generate an array to be used purely for the sorting order.
array_multisort(array_map(function($v){return strtotime(strstr($v,'-',true));},$wedTrackTimes),$wedTrackTimes);
For anyone that is lost in that syntax, here is the same functionality on more lines.
Code: (Demo)
$wedTrackTimes=[
"9:30 AM-10:30 AM",
"8:15 AM-9:15 AM",
"12:30 PM-1:30 PM",
"2:00 PM-3:00 PM",
"3:30 PM-4:30 PM"
];
foreach($wedTrackTimes as $time){ // iterate the time strings
$timestamps[]=strtotime(strstr($time,'-',true)); // store the first time of the time range as a unix timestamp
}
array_multisort($timestamps,$wedTrackTimes); // use $timestamps to sort $wedTrackTimes
var_export($wedTrackTimes);
Output:
array (
0 => '8:15 AM-9:15 AM',
1 => '9:30 AM-10:30 AM',
2 => '12:30 PM-1:30 PM',
3 => '2:00 PM-3:00 PM',
4 => '3:30 PM-4:30 PM',
)