PHP使用日期变量构建一个未知大小的数组


PHP build an array of an unknown size using date variables

我正在努力构建以下内容:

我需要的结果:

$months = array();
$months
(
    month[0] = '2011-10-1'
    month[1] = '2011-11-1'
    month[2] = '2011-12-1'
    month[3] = '2012-1-1'
)

来自以下变量:

$date = '2011-10-1';
$numberOfMonths = 4; 

如有任何帮助,我们将不胜感激。

谢谢,伙计们。。。所有这些解决方案都有效。我接受了最适合我使用的。

您可以使用一个简单的循环和strtotime():

$date = '2011-10-1';
$numberOfMonths = 4; 
$current = strtotime($date);
$months = array();
for ($i = 0; $i < $numberOfMonths; $i++) {
  $months[$i] = date('Y-n-j', $current);
  $current = strtotime('+1 month', $current);
}
$date = DateTime::createFromFormat('Y-m-j', '2011-10-1');
$months = array();
for ($m = 0; $m < $numberOfMonths; $m++) {
   $next = $date->add(new DateInterval("P{$m}M"));
   $months[] = $next->format('Y-m-j');
}
<?php
function getNextMonths($date, $numberOfMonths){
    $timestamp_now = strtotime($date);
    $months[] = date('Y-m-d', $timestamp_now);
    for($i = 1;$i <= $numberOfMonths; $i++){
          $months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
    }
    print_r($months);
}
getNextMonths('2011-10-1', 4);

工作演示

您可以在date上使用split,然后在一个月内使用for循环。诀窍是使用类似的东西

$newMonth = ($month + $i) % 12 + 1;

(%被称为模,它可以做你想要的事情。(