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


PHP Date range array for the last 40 sundays

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

尝试以下

$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);
}

应该可以工作:

<?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);
?>

查看示例

<?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);

查看实际效果

是的,当然。使用此代码

$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;  
}