我制作了一个php函数,计算从现在到52周的几周,然后从第1周开始再次向左开始几周。
我想知道是否有更简单的方法来做到这一点,或者我做了一个正确的功能。
这是我的代码:
function weeks($start_week)
{
$start_week = str_replace("0", "", $start_week); // from week 1 tot 9 remove the zero's.
$offset_week = $start_week - 1; // when the loop reach week 52, start with new weeks minus 1
$last_week = 52; // Last week of the year
$aantal_weken = 52; // # of weeks in a year
for($start_week; $start_week <= $aantal_weken; $start_week++)
{
echo $start_week.", ";
if($start_week == $last_week)
{
$new_weeks = 1; // when we reach week 52, set a new variable tot first week of the year
for($new_weeks; $new_weeks <= $offset_week; $new_weeks++)
{
echo $new_weeks.", ";
}
}
}
return $start_week;
}
$date = date("W");
weeks($date);
输出:
4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27 ,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52 ,1,2,3,
答案 0 :(得分:3)
返回数周范围的数组:
function weeks($start_week) {
$last_week = date_format(date_create('December 28th'), 'W');
$range = range(1, $last_week);
return array_merge(
array_slice($range, $start_week - 1),
array_slice($range, 0, $start_week - 1)
);
}
答案 1 :(得分:1)
您的问题实际上与日期无关。它只与数学有关。请尝试以下代码:
function weeks($start_week) {
$arr = array();
for ($i = 0; $i < 52; $i++) {
$arr[] = ($i + $start_week - 1) % 52 + 1;
}
return implode(', ', $arr);
}
echo weeks(4);
答案 2 :(得分:0)
function weeks($start_week)
{
$start_week = str_replace("0", "", $start_week); // from week 1 tot 9 remove the zero's.
$offset_week = $start_week - 1; // when the loop reach week 52, start with new weeks minus 1
$last_week = 52; // Last week of the year
$aantal_weken = 52; // # of weeks in a year
for($start_week; $start_week <= $aantal_weken; $start_week++)
{
echo $start_week.", ";
if($start_week == $last_week)
{
$new_weeks = 1; // when we reach week 52, set a new variable tot first week of the year
for($new_weeks; $new_weeks <= $offset_week; $new_weeks++)
{
echo $new_weeks.", ";
}
}
}
return $start_week;
}
$date = date("W");
weeks($date);