我有以下带有开始时间和结束时间的数组(都保存在数据库中)
$cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
我想显示预订时间(保存在数据库中)和可用时间,我尝试使用以下代码
$start = "09:30";
$end = "10:30";
$availability = array_combine($cars, array_map(function ($v) use ($start, $end) {
return (strtotime($v) < strtotime($start) || strtotime($v) > strtotime($end)) ? 'available' : 'booked'; },
$cars));
显示结果
Array
(
[09:00] => available
[09:30] => booked
[10:00] => booked
[10:30] => booked
[11:00] => available
[11:30] => available
[12:00] => available
[12:30] => available
)
但是我有多个开始时间和结束时间(动态地),所以如何获得结果(如上)?
答案 0 :(得分:1)
<?php
$times = array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
$availability = array_fill_keys($times, 'available');
function book(&$availability, $start, $end)
{
foreach($availability as $k => $v)
if(strtotime($k) >= strtotime($start) && strtotime($k) <= strtotime($end))
$availability[$k] = 'booked';
}
book($availability, '09:30', '10:30');
book($availability, '11:30', '12:00');
print_r($availability);
输出:
Array
(
[09:00] => available
[09:30] => booked
[10:00] => booked
[10:30] => booked
[11:00] => available
[11:30] => booked
[12:00] => booked
[12:30] => available
)