PHP使用日期变量构建未知大小的数组
我正在努力构建以下内容: 结果我需要:PHP使用日期变量构建未知大小的数组,php,Php,我正在努力构建以下内容: 结果我需要: $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; 任何帮助都将不胜感激 谢谢,伙计们。。。所有这些解决方案都有效。我接受了最适合我
$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;
任何帮助都将不胜感激
谢谢,伙计们。。。所有这些解决方案都有效。我接受了最适合我使用的 您可以使用简单的循环和:
$date='2011-10-1';
$numberOfMonths=4;
$current=strottime($date);
$months=array();
对于($i=0;$i<$numberOfMonths;$i++){
$months[$i]=日期('Y-n-j',$current);
$current=strotime(“+1个月,$current”);
}
您可以使用简单的循环和:
$date='2011-10-1';
$numberOfMonths=4;
$current=strottime($date);
$months=array();
对于($i=0;$i<$numberOfMonths;$i++){
$months[$i]=日期('Y-n-j',$current);
$current=strotime(“+1个月,$current”);
}
您可以在日期使用拆分,然后在一个月内使用for
循环。诀窍是使用类似
$newMonth = ($month + $i) % 12 + 1;
(%
被称为模,并且完全按照您的要求进行。)您可以在日期使用拆分,然后在一个月内使用进行循环。诀窍是使用类似
$newMonth = ($month + $i) % 12 + 1;
(%
被称为模,并且完全按照您的要求执行。)$date=DateTime::createFromFormat('Y-m-j','2011-10-1');
$months=array();
对于($m=0;$m<$numberOfMonths;$m++){
$next=$date->add(新的日期间隔(“P{$m}m”));
$months[]=$next->format('Y-m-j');
}
$date=DateTime::createFromFormat('Y-m-j','2011-10-1');
$months=array();
对于($m=0;$m<$numberOfMonths;$m++){
$next=$date->add(新的日期间隔(“P{$m}m”));
$months[]=$next->format('Y-m-j');
}
PHP的好解决方案>=5.3.0 PHP的好解决方案>=5.3。0@nachito:天哪,这是漫长的一周!谢谢你指出这一点,修正:-)@nachito:天哪,这是漫长的一周!感谢您指出,修正:-)这不考虑下一年?不,但您可以在$month==1时增加年份。这不考虑下一年?不,但您可以在$month==1时增加年份
$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);