PHP: while循环中减去1年时年份不变

PHP: Year does not change when subtracting 1 year in while loop

我想按降序显示从当年到 2014 年的所有年份。但是,当我尝试循环并减去包含年份值的变量时,它并没有改变。一直到 2020 年。我错过了什么?这是我的代码:

$curyear = date("Y");
while ($curyear > "2014"){
      $subyear = date('Y', strtotime($curyear. ' - 1 year'));
      $curyear = $subyear;
      echo $curyear;
}

您不必减去 'year' 类型,您可以像这样直接减去 subtract 1

$curyear = date("Y");
while ($curyear > "2014"){
     $curyear = $curyear -1;
     echo $curyear;
}

您传递给 strtotime 函数的日期时间格式不明确,例如:

# Current datetime: 2021-06-29 14:41:05
# Only the third print meets your expectations
echo date('Y-m-d H:i:s', strtotime('2021 - 1 year')), PHP_EOL; # 2020-06-29 20:21:00, 2021 -> 20:21:00
echo date('Y-m-d H:i:s', strtotime('2001 - 1 year')), PHP_EOL; # 2020-06-29 20:01:00, 2001 -> 20:01:00
echo date('Y-m-d H:i:s', strtotime('1999 - 1 year')), PHP_EOL; # 1998-06-29 14:41:05, 1999 - 1 -> 1998

而且很容易修复,结合年月日来防止歧义:

$curyear = date("Y");
while ($curyear > "2014"){
      # $subyear = date('Y', strtotime($curyear. ' - 1 year'));
      $subyear = date('Y', strtotime("$curyear-01-01 - 1 year"));
      $curyear = $subyear;
      echo $curyear;
}