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



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

你是如何得到这个数组中的中间天数的?答:周一、周二、周三。

案例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

我已经创建了这个函数,它可以实现这一点,注释将引导您了解它是如何实现的。

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

最新更新