2012-05-31 27 views
4

我需要前六個月的清單,並使用下面的代碼。最近六個月在PHP中的列表

for ($i=6; $i >= 1; $i--) { 
    array_push($months, date('M', strtotime('-'.$i.' Month'))); 
} 

print_r($months); 

它給出了錯誤的輸出如下

Array 
(
    [0] => 'Dec' 
    [1] => 'Dec' 
    [2] => 'Jan' 
    [3] => 'Mar' 
    [4] => 'Mar' 
    [5] => 'May' 
) 

它必須是

Array 
(
    [0] => 'Nov' 
    [1] => 'Dec' 
    [2] => 'Jan' 
    [3] => 'Feb' 
    [4] => 'Mar' 
    [5] => 'Apr' 
) 

如果我錯了。請幫助

+1

問題是「月」沒有按照您的想法定義。它是第31和所有。因此,第5個月的第31個月減去1個月是第4個月的第31個月。這顯然是第一個月的第一次。 – Nanne

+0

@Nanne你應該把那作爲一個答案,很好的解釋:) –

+0

@siganteng感謝,但我沒有時間來測試實際上可以有用的東西作爲一種解決方案,所以它只有一半是什麼smk3108需要:) – Nanne

回答

10

您需要從月份的第一天開始計算。

$first = strtotime('first day this month'); 
$months = array(); 

for ($i = 6; $i >= 1; $i--) { 
    array_push($months, date('M', strtotime("-$i month", $first))); 
} 

print_r($months); 

/* 
Array 
(
    [0] => Nov 
    [1] => Dec 
    [2] => Jan 
    [3] => Feb 
    [4] => Mar 
    [5] => Apr 
) 

*/ 
+0

輸出不像OP想要的那樣。 – k102

+0

@ k102我更正了代碼。謝謝。 – flowfree

+0

$ first = strtotime('上個月的第一天'); $ months = array(); 爲($ i = 6; $ I <= 1;我 - $){ array_push($個月,日期( 'M',的strtotime( 「 - $ I月」,$第一))); }適用於一項更改。 – smk3108

0

使用這一個:

date('M',strtotime('-'.$i.' Month', strtotime(date('Y-m-01')))) 

原因:因爲今天是五月31日,而不是埃夫裏每月有31天。這實際上(我的意思是+/-月)功能並不那麼可靠。你能猜到這一個的輸出是什麼:

print(date('Y-M-d',strtotime('+1 Month', strtotime(date('2012-01-30'))))."\n"); 

3

和往常一樣我張貼這樣做的目的的方法:

$startDate = new DateTime('first day of this month - 6 months'); 
$endDate = new DateTime('last month'); 
$interval = new DateInterval('P1M'); // P1M => 1 month per iteration 

$datePeriod = new DatePeriod($startDate, $interval, $endDate); 

foreach($datePeriod as $dt) { 
    array_push($months, $dt->format('M')); 
} 

/* output: 
Array 
(
    [0] => Nov 
    [1] => Dec 
    [2] => Jan 
    [3] => Feb 
    [4] => Mar 
    [5] => Apr 
) 
*/ 

DateTimeDateIntervalDatePeriod進一步的信息。