得到过去X周的周数

时间:2013-09-09 09:58:15

标签: php date date-range

我有一个脚本,可以像过去那样构建过去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 个答案:

答案 0 :(得分:5)

一个想法

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

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

$i++;
}

答案 1 :(得分:2)

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

$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1)  $week_numbers[$key] += 52; }

答案 2 :(得分: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在几个月内进行类似的事情。

答案 3 :(得分: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