Reputation: 288
I have this associate array below
["12:00" => "Lunch", "07:00" => "Arrival", "07:15" => "Start Tour"]
I want to print it in as below ascending by time (key)
7:00 => Arrival
7:15 => Start Tour
12:00 => Lunch
So far what I've tried is below
$arr = ["12:00" => "Lunch", "07:00" => "Arrival", "07:15" => "Start Tour"];
function timecomp($a,$b)
{
// Subtracting the UNIX timestamps from each other.
// Returns a negative number if $b is a date before $a,
// otherwise positive.
return strtotime($b[0])-strtotime($a[0]);
}
uasort($arr,'timecomp');
print_r($arr);
It print this
Array
(
[07:15] => Start Tour
[07:00] => Arrival
[12:00] => Lunch
)
Upvotes: 1
Views: 99
Reputation: 53573
As long as your time strings use 24-hour hours and leading zeroes, you can just use ksort()
:
$a = ["12:00" => "Lunch", "07:00" => "Arrival", "07:15" => "Start Tour"];
ksort($a);
print_r($a);
Result:
Array
(
[07:00] => Arrival
[07:15] => Start Tour
[12:00] => Lunch
)
Upvotes: 7