【问题标题】:Calculate intermediate week days between two week days In PHP在PHP中计算两个工作日之间的中间工作日
【发布时间】:2019-05-03 00:25:59
【问题描述】:

给定两个工作日:周一、周三。

您如何获得该数组中的中间天数? 答:周一、周二、周三。

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

谢谢!

【问题讨论】:

  • 到目前为止你有没有尝试过?
  • 你可以创建一个数组,列出星期一到星期日两次,循环它,如果天等于开始日则开始输出,停止检查开始日,如果日等于结束日则停止循环。
  • 周六和周日不被视为“工作日”,它们是“周末”。那么在星期一到星期一的示例中,是否应该从输出中省略这些内容?
  • 这种情况下周六周日也要考虑
  • 太好了,试试我的建议,如果遇到困难,请返回您尝试的代码。

标签: php weekday


【解决方案1】:

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

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

【讨论】:

  • 我最初打算做这样的事情,但我卡住了。我看到你使用了count($days)>1,如果我想到我会有类似的解决方案:D
【解决方案2】:

我创建了这个函数来执行此操作,cmets 将引导您了解它是如何完成的。

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

【讨论】:

  • @lolo 我实际上似乎犯了一个错误,检查答案中的当前代码以修复它。基本上是错误的,所以如果你在星期二->星期二、星期三->星期三等(基本上是星期一->星期一以外的任何时间),它会错误地返回。
猜你喜欢
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 2018-08-03
  • 2014-10-20
  • 1970-01-01
  • 2012-02-13
相关资源
最近更新 更多