使用键作为时间对数组进行排序,格式为xx:xx

使用键作为时间对数组进行排序,格式为xx:xx

问题描述:

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
)

我在下面有这个关联数组 p>

  [“12:  00“=>  “午餐”,“07:00”=>  “抵达”,“07:15”=>  “开始游览”] 
  code>  pre> 
 
 

我想按时间(按键)升序打印下来 p>

   7:00 => 到达
7:15 => 开始游览
12:00 => 午餐
  code>  pre> 
 
 

到目前为止,我尝试过的是 p>

  $ arr = [“12:00”  =>  “午餐”,“07:00”=>  “抵达”,“07:15”=>  “开始游览”]; 
 
函数timecomp($ a,$ b)
 {
 //从彼此中减去UNIX时间戳。
如果$ b是$ a之前的日期,则返回一个负数 ,
 //否则为正。
返回strtotime($ b [0]) -  strtotime($ a [0]); 
} 
uasort($ arr,'timecomp'); 
 
print_r($ arr  ); 
  code>  pre> 
 
 

打印此 p>

  Array 
(
 [07:15] => 开始游览
 [07:00] =>到达
 [12:00] =>午餐
)
  code>  pre> 
  div>

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
)