过去40个星期日的PHP日期范围数组

时间:2013-09-25 12:48:45

标签: php arrays date

有没有办法将最后40个星期日用php放入数组?我现在不明白。

尝试了以下

$week_array = array();
$last_s = date('Y-m-d',strtotime('last sunday'));
array_push($week_array, $last_s);       
for ($i = 0; $i <= 40; $i++ ) {
  $last_s = $last_s - 7;
  array_push($week_array, $last_s);
}

3 个答案:

答案 0 :(得分:1)

<?php
$sundays = array();
$now = new DateTime();
if ($now->format('l') === 'Sunday') {
    $sundays[] = $now->format("Y-m-d");
}
$dt = new DateTime('last sunday');
while (count($sundays) < 40) {
    $sundays[] = $dt->format("Y-m-d");
    $dt->modify('-1 week');
}
print_r($sundays);

<强> See it in action

答案 1 :(得分:1)

应该有效:

<?php
for ($i = 0; $i < 40 ; $i++){
   $week = 3600*24*7; 
   $dates[] = date("Y-m-d",strtotime(date("Y-m-d",strtotime("last Sunday")))-$week*$i) ;

}
print_r($dates);
?>

<强> see example

答案 2 :(得分:0)

是的,当然。使用此代码

$sundays = array();

// $prev is auxillary variable which holds the time 
// from which we are searching the next last Sunday
$prev = time();

for($i = 0; $i < 40; $i++)
{
  $prev = strtotime('last Sunday', $prev);  // 
  $sundays[] = $prev;  
}