从数组中获取时间间隔/空闲时间

假设有人需要预订房间。客房预订服务的开放时间为 08:00:00 至 18:00:00。所以预约时间有限:


array:2 [▼

  0 => "08:00:00"

  1 => "18:00:00"

]

而且房间也可能有一些已经预定的时间,应该是这样的:


array:3 [▼

  0 => array:2 [▼

    0 => "08:05:00"

    1 => "09:00:00"

  ]

  1 => array:2 [▼

    0 => "10:00:00"

    1 => "15:00:00"

  ]

  2 => array:2 [▼

    0 => "16:00:00"

    1 => "17:00:00"

  ]

]

我想做的是找到时间间隔,结果应该是这样的:


array:4 [▼


  0 => array:2 [▼

    0 => "8:00:00"

    1 => "8:05:00"

  ]

  1 => array:2 [▼

    0 => "9:00:00"

    1 => "10:00:00"

  ]

  2 => array:2 [▼

    0 => "15:00:00"

    1 => "16:00:00"

  ]

  3 => array:2 [▼

    0 => "17:00:00"

    1 => "18:00:00"

  ]

]


看来我必须先对预定时间数组进行排序,然后再对数组进行补充。但是如何在 PHP 代码中实现它。有人可以帮我解决这个问题吗?提前谢谢。


守着星空守着你
浏览 77回答 1
1回答

30秒到达战场

如果您的预订未按开始时间排序,则需要对其进行排序。然后您可以遍历预订,在一个预订结束和下一个预订开始之间创建空闲时间条目。请注意,由于您的时间是HH:mm:ss格式,您可以直接将它们作为字符串进行比较;无需将它们转换为整数时间值。$hours = ["08:00:00", "18:00:00"];$bookings = [["10:00:00", "15:00:00"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;["08:05:00", "09:00:00"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;["16:00:00", "17:00:00"]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;];$start = $hours[0];$end = $hours[1];// sort the bookings$bstart = array_column($bookings, 0);array_multisort($bstart, $bookings);// get the free times$time = $start;$bindex = 0;$free = array();while ($time < $end && $bindex < count($bookings)) {&nbsp; &nbsp; if ($time < $bookings[$bindex][0]) {&nbsp; &nbsp; &nbsp; &nbsp; $free[] = [$time, $bookings[$bindex][0]];&nbsp; &nbsp; }&nbsp; &nbsp; $time = $bookings[$bindex][1];&nbsp; &nbsp; $bindex++;}// end of day free?if ($time < $end) {&nbsp; &nbsp; $free[] = [$time, $end];}print_r($free);输出:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 08:00:00&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 08:05:00&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 09:00:00&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 10:00:00&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [2] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 15:00:00&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 16:00:00&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [3] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 17:00:00&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 18:00:00&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP