2014-01-13 142 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; 
}