PHP中如何遍历日期数组并移除所有过去的日期?
移除数组中所有过去日期的解决方案
你的问题在于当前代码只检查并移除了排序后的第一个过去日期,而没有遍历整个数组处理所有不符合条件的元素。下面提供两种高效的实现方式:
方法一:使用array_filter(推荐,简洁高效)
array_filter可以直接帮你筛选出符合条件的元素,不需要手动遍历和删除:
// 获取今日的时间戳(仅日期部分,忽略时间) $today_timestamp = strtotime(date("Y-m-d")); // 过滤出所有event_date大于等于今日的元素 $future_dates = array_filter($primary_dates, function($date_item) use ($today_timestamp) { $event_timestamp = strtotime($date_item['event_date']); return $event_timestamp >= $today_timestamp; }); // 如果需要重新索引数组(因为array_filter会保留原索引) $future_dates = array_values($future_dates); print_r($future_dates);
解释:
array_filter会遍历数组的每个元素,将满足回调函数条件的元素保留下来use ($today_timestamp)让回调函数能访问外部的今日时间戳变量array_values用来重置数组索引,避免过滤后出现不连续的索引
方法二:手动遍历数组删除过去日期
如果你更倾向于手动处理,可以用foreach循环遍历数组,删除不符合条件的元素:
$today_timestamp = strtotime(date("Y-m-d")); foreach ($primary_dates as $key => $date_item) { $event_timestamp = strtotime($date_item['event_date']); if ($event_timestamp < $today_timestamp) { unset($primary_dates[$key]); } } // 重新索引数组(可选) $primary_dates = array_values($primary_dates); print_r($primary_dates);
补充:修正你的排序代码
你之前的usort回调函数返回布尔值是不符合要求的,正确的逆时间排序写法应该返回整数差值:
usort($item['event_dates_1'], function ($a, $b) { return strtotime($b['event_date']) - strtotime($a['event_date']); });
这样才能保证数组是正确的逆时间顺序排列。
内容的提问来源于stack exchange,提问作者StephenMeehan
相关产品推荐
相关产品推荐

