显示营业时间表

时间:2020-05-24 12:12:37

标签: php arrays

"hours" => 
        [
            'Sun' => ['00:00' => '02:00', '18:00' => '23:59'],
            'Mon' => ['00:00' => '02:00'],
            'Tue' => NULL,
            'Wed' => NULL,
            'Thu' => ['18:00' => '23:59'],
            'Fri' => ['00:00' => '02:00', '18:00' => '23:59'],
            'Sat' => ['00:00' => '02:00', '18:00' => '23:59'],
        ],

我有一家餐厅的营业时间。餐厅的营业时间为下午6点至凌晨02点。 显示类似于Google的PHP表的最佳方法是什么? Google table

当我尝试使用数组显示时,无法修改输出以将“ 02am”视为前一天的一部分。

我无法修改数组的结构,该结构已在其他地方使用。

1 个答案:

答案 0 :(得分:1)

尽管有一种更简单的方法可以执行此操作,因为时间似乎都一样,这意味着您可以对某些值进行硬编码,但我认为这可以改变。

此代码需要一个开始时间和该位置开放的小时数。然后,它可以据此生成关闭时间。

$hours = [
    'Sun' => [
        'open' => '18:00',
        'closed' => '+8 hours'
    ],
    'Mon' => null,
    'Tue' => null,
    'Wed' => null,
    'Thu' => [
        'open' => '18:00',
        'closed' => '+8 hours'
    ],
    'Fri' => [
        'open' => '18:00',
        'closed' => '+8 hours'
    ],
    'Sat' => [
        'open' => '18:00',
        'closed' => '+8 hours'
    ],
];

foreach ($hours as $day => $time) {
    if ($time === null) {
        printf('%s Closed%s', $day, PHP_EOL);
        continue;
    }
    $open = new DateTimeImmutable($time['open']);
    $closed = $open->modify($time['closed']);
    printf('%s %s %s %s', $day, $open->format('H:i'), $closed->format('H:i'), PHP_EOL);
}

输出

Sun 18:00 02:00 
Mon Closed
Tue Closed
Wed Closed
Thu 18:00 02:00 
Fri 18:00 02:00 
Sat 18:00 02:00 

Demo