2014-01-13 88 views
0

我如何循环过去的12个月以及未来的12个月。获取12个月的未来12个月的过去

我imainge最简单的方法就是通过开始一年前的循环来过去24个月,例如, 2015年1月

我当前的代码返回过去12个月

for ($i = 1; $i <= 12; $i++) { 
$my = date("F Y", strtotime(date('Y-m-01')." -$i months")); 
$ymd = date("Y-m-d", strtotime(date('Y-m-01')." -$i months")); 

回答

0

试试这个

for ($i = 1; $i <= 12; $i++) 
{ 
$my = date("F Y", strtotime(date('Y-m-01')." -$i months")); 
$ymd = date("Y-m-d", strtotime(date('Y-m-01')." -$i months")); 

$f_my = date("F Y", strtotime(date('Y-m-01')." +$i months")); 
$f_ymd = date("Y-m-d", strtotime(date('Y-m-01')." +$i months")); 

} 
2

这可以简单地通过DateTime扩展来完成:

$months = 12; # number of months before and after current month 
$dt = new DateTime('first day of this month'); # select first day in current month 
$dt->modify("-$months month"); 
for ($i = 0; $i <= $months * 2; $i++) { 
    echo $dt->format('M Y'), "\n"; 
    $dt->modify('+1 month'); 
} 

demo

+0

** [这里是这里所有的答案有点基准。(http://pastebin.com/sbZ1ptS5)** –

0
$arrPast = array(); 
$arrFut = array(); 
for ($i = 1; $i <= 12; $i++) { 
    $arrPast[] = date("Y-m-d", strtotime(date('Y-m-d')." -$i months")); 
    $arrFut[] = date("Y-m-d", strtotime(date('Y-m-01')." +$i months")); 
} 

echo 'Past 12 months <pre>'; 
print_r($arrPast); 

echo 'Future 12 months <pre>'; 
print_r($arrFut); 
0

应该是这样

$pastDate = date("Y-m-d", strtotime(date('Y-m-01')." -12 months")); 

$futureDate = date("Y-m-d", strtotime(date('Y-m-01')." +12 months")); 

for ($i = $pastDate; $i <= $futureDate; $i = date("Y-m-d", strtotime($i." +1 months"))) 
{ 
    echo "<br />Current Month(Y-m-d) is ".$i; 
}