开发者

PHP build an array of an unknown size using date variables

I'm struggling with how to build the following:

result I need:

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

from the fol开发者_运维技巧lowing variables:

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

Any help would be appreciated.

Thanks, guys... all of these solutions work. I accepted the one that works best for my usage.


You can do it using a simple loop and 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);

Working demo


You could use split on date and then a for loop over the month. The trick is to use something like

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

(% is called modulo and does exactly what you want.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜