PHP实现:如何过滤数组中早于当前时间的时间值
问题分析与解决方案
原代码未生效的核心问题如下:
array_search($current_time, $time_slot)找不到目标值(数组里没有4:00),导致整个处理逻辑从未执行- 直接用字符串比较时间会出现逻辑错误,比如字符串
15:00会被判定为小于4:00(因为首字符1<4) - 代码仅尝试处理与
$current_time相等的元素,没有遍历过滤所有早于当前时间的项
正确实现方式
要准确过滤早于当前时间的项,建议先将时间字符串转换为可直接比较的数值(如总分钟数),再进行过滤操作:
方法一:使用array_filter(简洁高效)
$current_time = '4:00'; $time_slot = ['1:00','3:00','15:00','19:00']; // 辅助函数:把时间字符串转为总分钟数 function timeToMinutes($time) { list($hour, $minute) = explode(':', $time); return (int)$hour * 60 + (int)$minute; } $currentMinutes = timeToMinutes($current_time); // 过滤出大于等于当前时间的项 $filteredTimeSlot = array_filter($time_slot, function($time) use ($currentMinutes) { return timeToMinutes($time) >= $currentMinutes; }); // 可选:重置数组索引(如果需要连续索引的话) $filteredTimeSlot = array_values($filteredTimeSlot); print_r($filteredTimeSlot);
执行后输出:
Array ( [0] => 15:00 [1] => 19:00 )
方法二:使用foreach遍历删除
如果习惯手动遍历处理,也可以用循环逐个判断删除:
$current_time = '4:00'; $time_slot = ['1:00','3:00','15:00','19:00']; function timeToMinutes($time) { list($hour, $minute) = explode(':', $time); return (int)$hour * 60 + (int)$minute; } $currentMinutes = timeToMinutes($current_time); foreach ($time_slot as $key => $time) { if (timeToMinutes($time) < $currentMinutes) { unset($time_slot[$key]); } } // 可选:重置数组索引 $time_slot = array_values($time_slot); print_r($time_slot);
内容的提问来源于stack exchange,提问作者YourDeveloper
相关产品推荐
相关产品推荐

