过滤日期的多维数组以排除周末(周六和周日)

问题描述 投票:0回答:3

我正在循环遍历当前月份的一组天数,以生成当天或当天之后的另一天数组,并且效果很好。我现在需要排除/省略任何日期(如果是星期六或星期日)。

我正在尝试确定是否可以包含周六/周日日期的检查,例如:

date('N', strtotime($day)) >= 6);

使用我现有的生成数组的代码:

// Get days for current month
    $day = date("Y-m-d");
    $i = strtotime($day);
    
    array("year" => array("month" => array(days)));
    $allDays = array(
        date('Y', $i) => array(
            date('n') => range(date('d', $i), intval(date('t'))),
        ),
    );

不确定如何将周末约会的测试与此结合起来,或者我是否需要在此处使用 for 循环等?

php arrays date filtering weekday
3个回答
1
投票

假设您正在尝试获取当月不包括周末的所有日期:您可以使用

array_filter()
和回调来获取周末日期,然后使用
array_diff()
创建一个包含以下内容的新数组:仅工作日:

$year = date('Y');
$month = date('n');

$weekend_days = array_filter($allDays[$year][$month], function($d) {
    return (date('N', strtotime(date("Y-m-$d"))) >= 6);
});

$allDays[$year][$month] = array_diff($allDays[$year][$month], $weekend_days);

print_r($allDays);

0
投票

您可以在将每个值添加到数组之前检查日期:

if (!in_array(date('w', $i), array('0', '6')))
{
    // add $i to array
}

0
投票

您可能希望从一开始就填充所需的数组,而不是过滤填充的多维数组。

声明当月第一天的日期时间对象。 缓存月份值以供将来参考。 将日期回退一天以到达上个月的最后一天。 使用短语“下一个工作日”将对象前进到下一个所需的日期。 将符合条件的日期以所需的格式推入结果数组中。

代码:(演示

$result = [];
$dt = new DateTime('first day of this month');
$month = $dt->format('n');
$dt->modify('-1 day');
while ($dt->modify('next weekday') && $dt->format('n') == $month) {
    $result[$dt->format('Y')][$dt->format('n')][] = $dt->format('d');
}
var_export($result);

作为此实现的扩展,可以以类似的方式填充多年数组。

结果是一个数组,其中年份值作为第一级键,月份值作为第二级键,weekdays作为第三级值。

$result = [];
foreach ([2023, 2024] as $year) {
    $dt = new DateTime("$year-01-01 -1 day");
    while ($dt->modify('next weekday') && $dt->format('Y') == $year) {
        $result[$year][$dt->format('n')][] = $dt->format('d');
    }
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.