【发布时间】:2020-10-10 15:56:30
【问题描述】:
我想在一个小时数组中找到下一个最近的小时,我有下面的代码可以在前后两个方向上搜索最近的小时。
我需要做的是只搜索下一个小时,在下面的示例中应该是 14:00 而不是 03:50。
条件详情:
- 持续时间:24H - 1D
- 开始时间:00:00
- $timeslots 和 $expected_time 中的值都是动态的
$timeslots = ["01:00","01:30","02:00","02:30","00:30","01:00","01:30","02:00","02:30","03:50", "14:00"];
$expected_time = "04:00";
$timestamp = strtotime($expected_time);
$diff = null;
$index = null;
foreach ($timeslots as $key => $time) {
$currDiff = abs($timestamp - strtotime($time));
if (is_null($diff) || $currDiff < $diff) {
$index = $key;
$diff = $currDiff;
}
}
echo $timeslots[$index];
【问题讨论】:
-
你想找到什么?基于什么参数?你能提供更多的例子吗?
-
不清楚 1)为什么$timeslots 数组没有排序; 2)如果最近的 next 插槽无论如何都应该被占用,为什么有人试图计算两次之间的模差。
-
你没有指定最接近对你意味着什么。