You need to enable JavaScript to run this app. PHP如何用array_filter筛选数组中匹配自定义月份字段的条目
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何用array_filter筛选数组中匹配自定义月份字段的条目

解决方法

核心错误说明

你原有筛选逻辑存在两个问题:

  • array_filter默认只会将数组元素的值传入回调函数,外部定义的$productMonth无法直接在回调中获取,需要用use语法引入
  • $var.date('F')的逻辑完全错误:该写法是把周五日期字符串和当前系统月份做拼接,你实际需要的是从周五日期字符串中提取月份,再和$productMonth对比

正确实现代码

直接替换你原有$fridaysUnique = array_unique($fridays);之后的逻辑即可:

// 筛选符合月份的周五日期
$filteredFridays = array_filter($fridaysUnique, function($fridayStr) use ($productMonth) {
    // 从日期字符串中提取月份全称,和目标字段对比
    return date('F', strtotime($fridayStr)) === $productMonth;
});

下拉框遍历部分同步修改为遍历筛选后的数组即可,还可以顺便给option加上标准日期格式的value,方便后续业务处理:

<select>
<?php foreach ( $filteredFridays as $friday ) : ?>
    <option value="<?php echo date('Y-m-d', strtotime($friday)); ?>"><?php echo $friday; ?></option>
<?php endforeach; ?>
</select>

代码优化建议

你原有手动写10次逻辑生成周五的写法冗余,还会出现部分月份没有第五个周五导致重复值的问题,可以改成循环自动生成,不需要单独去重:

<?php
$productMonth = get_field('product_month');
$fridays = [];
// 定义时间范围:本月初到次月末
$monthEnd = strtotime('last day of next month');
$currentFriday = strtotime('first friday of this month');
// 循环生成范围内所有周五
while ($currentFriday <= $monthEnd) {
    $fridays[] = date('l jS F', $currentFriday);
    $currentFriday = strtotime('+1 week', $currentFriday);
}

// 筛选逻辑保持不变
$filteredFridays = array_filter($fridays, function($fridayStr) use ($productMonth) {
    return date('F', strtotime($fridayStr)) === $productMonth;
});
?>

优化后逻辑更简洁,自动适配当月、次月的周五数量,不会出现无效重复值。

内容的提问来源于stack exchange,提问作者MayhemBliz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 15:36:04