基于12小时定制时钟的排序数组

时间:2016-10-29 21:30:12

标签: php arrays sorting time

我的数组如下:

Array ( [01:00 pm] => Lunch [03:00 pm] => Dance [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing )

我需要将这些键转换为自定义时间格式进行排序,以便正确的顺序如下所示:

Array ( [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing [01:00 pm] => Lunch  [03:00 pm] => Dance )

但并非全部。这些派对通常在凌晨1点或凌晨2点结束。因此,以3am为第一个值启动时钟是有意义的。因此,02:00 am条目将出现在排序列表的末尾,并且最开始的05:00 am条目将出现在开头(因为我想将03:00 am指定为时钟的开头。

如果我在阵列中有一个02:00 am和05:00 am的例子,它将显示为:

Array ( [05:00 am] => Wake up [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing [01:00 pm] => Lunch  [03:00 pm] => Dance [02:00 am] => Party ends)

我不知道在哪里或如何从数组中转换键。我目前有:

 ksort($event_order);
                foreach ( $event_order as $time => $event) {
                    echo '<div><strong>';
                    echo $time;
                    echo '</strong> - ';
                    echo $event;
                    echo '</div>';
                }

1 个答案:

答案 0 :(得分:1)

这是一种方法,使用array_multisort,将时间字符串映射到午夜以来的秒数,并将前3个小时移动到结束:

$event_order = Array ( 
    "12:45 pm" => "Guests arrive",
    "12:55 pm" => "Blessing",
    "02:00 am" => "Party ends",
    "05:00 am" => "Wake up",
    "01:00 pm" => "Lunch",
    "03:00 pm" => "Dance",
    "12:50 pm" => "Find seats");

array_multisort(array_map(function ($v) {
    return (strtotime($v) - strtotime("midnight") + 21*3600) % (24*3600);
}, array_keys($event_order)), $event_order);

print_r($event_order);