2016-07-25 43 views
0

我無法找到一種方法來創建當前數組後的每個月的數組。在今天之後爲每個月創建一個數組

  <?php 
       $month = 07; 
       $year = 2016; 
       $end = date('Y'); 
       for($i=0;$i<=$end-$year;$i++){ 
        $from = 1; 
        if($i==0) 
         $from = $month; 


        for($y=$from;$y<=12;$y++){ 
         if($year==date('Y') && $y > date('m')) 
          break; 

         $a = $year+$i.'-'.$y; 
         $months[$a] = $a; 
        } 
       } 
       krsort($months); 
      ?> 
      <?php echo Html::dropDownList('month_year',$month_year,$months,array('class'=>'form-control'));?> 

我希望得到一個下拉列表,看起來像這樣

2016-09

2016-08

2016-07

對於來自每個月。開始日期應爲2016-07。最高值應該是當前月份。

回答

4

剛剛經歷他們創造一個開始和結束日期及循環:

$start = (new DateTime('next month'))->modify('first day of this month'); 
$end  = (new DateTime('+24 months'))->modify('first day of next month'); 
$interval = DateInterval::createFromDateString('1 month'); 
$period = new DatePeriod($start, $interval, $end); 

foreach ($period as $dt) { 
    echo $dt->format("Y-m") . "<br>\n"; 
} 

我用DateTime()DateInterval()DatePeriod(),因爲這是要做到這一點最清晰的方式和處理DST和閏年本身。

Demo

+0

感謝那些爲我工作,我只是修改開始固定和結束是當前月份。感謝您的解決方案:) –

相關問題