2

我有一个脚本可以构建过去 12 周的周数数组,如下所示:

$week_numbers = range(date('W'), date('W')-11, -1);

但是,如果当前周数是 1,那么这将返回一个数组,如下所示:

Array
(
    [0] => 1
    [1] => 0
    [2] => -1
    [3] => -2
    [4] => -3
    [5] => -4
    [6] => -5
    [7] => -6
    [8] => -7
    [9] => -8
    [10] => -9
    [11] => -10
)

但我需要这个数组看起来像这样:

Array
(
    [0] => 1
    [1] => 52
    [2] => 51
    [3] => 50
    [4] => 49
    [5] => 48
    [6] => 47
    [7] => 46
    [8] => 45
    [9] => 44
    [10] => 43
    [11] => 42
)

谁能看到一个简单的解决方案?

我想过做这样的事情(未经测试):

$current_week_number = date('W');

if($current_week_number<12){
    // Calculate the first range of week numbers (for current year)
    $this_year_week_numbers = range(date('W'), 1, -1);
    // Calculate the next range of week numbers (for last year)
    $last_year_week_numbers = range(52, 52-(11-$current_week_number), -1);
    // Combine the two arrays to return the week numbers for the last 12 weeks
    $week_numbers = array_merge($this_year_week_numbers,$last_year_week_numbers);
}else{
    // Calculate the week numbers the easy way
    $week_numbers = range(date('W'), date('W')-11, -1);
}
4

4 回答 4

5

一个想法

$i = 1;
while ($i <= 11) {

echo date('W', strtotime("-$i week")); //1 week ago

$i++;
}
于 2013-09-09T10:05:48.750 回答
2

如果你不害怕循环,你可以这样做:

$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1)  $week_numbers[$key] += 52; }
于 2013-09-09T10:03:45.600 回答
2

你可以做一个模%技巧:

$week_numbers = range(date('W'), date('W')-11, -1);
foreach ($week_numbers as $i => $number) {
    $week_numbers[$i] = (($week_numbers[$i] + 52 - 1) % 52) + 1;
}
// -1 +1 is to change the range from 0-51 to 1-52

我发现像这样使用模数对于日期计算通常很有用,你可以在几个月内使用类似的东西,使用12.

于 2013-09-09T10:04:21.440 回答
1

好吧,我认为最简单的方法是在获取日期后创建数组:

$week_numbers = array_map(function($iDay)
{
   return ($iDay+52)%52?($iDay+52)%52:52;
}, range(date('W'), date('W')-11));

-注意,你不能这样做,%因为 52%52 将是0(并且你想要52

于 2013-09-09T10:06:46.037 回答