在PHP中计算两周之间的中间工作日

时间:2018-11-30 20:27:36

标签: php weekday

给出两个工作日:星期一,星期三。

您如何获得阵列中的中间日期? 答:星期一,星期二,星期三。

案例2:从星期一到星期一 答:星期一,星期二,星期三,星期四,星期五,星期六,星期日,星期一

谢谢!

2 个答案:

答案 0 :(得分:2)

我已经创建了执行此功能的函数,注释会逐步引导您完成操作。

function list_days($start, $end) {

    //convert day "word" to it's given number
    //Monday = 1, Tuesday = 2 ... Sunday = 7
    $start_n = date('N', strtotime($start));
    $end_n = $end_range = date('N', strtotime($end));

    //we also set $end_range above, by default it's set to the $end day number, 
    //but if $start and $end are the same it will be changed later.

    //create an empty output array
    $output = [];

    //determine end_range for the for loop
    //if $start and $end are not the same, the $end_range is simply the number of $end (set earlier)
    if($start_n == $end_n) {

        //if $start and $end ARE the same, we know there is always 7 days between the days
        //So we just add 7 to the start day number.
        $end_range = $start_n + 7;
    }

    //loop through, generate a list of days
    for ($x = $start_n; $x <= $end_range; $x++) {

        //convert day number back to the readable text, and put it in the output array
        $output[] = date('l', strtotime("Sunday +{$x} days"));
    }

    //return a string with commas separating the words.
    return implode(', ', $output);
}

用法:

示例1:

echo list_days('Monday', 'Wednesday');
//output: Monday, Tuesday, Wednesday

示例2:

echo list_days('Monday', 'Monday');
//output: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Monday

答案 1 :(得分:2)

我的解决方案更多地是移动数组的内部指针直到找到边距,然后将边距之间的元素推入另一个结果数组。无论初始数组中包含什么数据,都可以使用。

function getDaysInBetween($start, $end)
    {
        $weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

        $start_found = false;

        $days = [];

        while(true) {
            $next = next($weekdays);
            $day = (empty($day) || !$next)?reset($weekdays):$next;

            if($day === $start) $start_found = true;

            if($start_found) {
                $days[] = $day;
                if($day===$end && count($days)>1) return implode(", ",$days);
            }

        }

    }

此处为现场演示:https://3v4l.org/D5063

相关问题