PHP将年份和月份添加到一个选择框中


PHP get years and month to a select box

我正在为过去几年的编写代码

<select>                                        
    <option value="03/2014">03/2014</option>                                        
    <option value="02/2014">02/2014</option>                                        
    <option value="01/2014">01/2014</option>                                        
    <option value="12/2013">12/2013</option>                                        
    <option value="11/2013">11/2013</option>                                        
    <option value="10/2013">10/2013</option>
 </select>

我使用这个代码,但我只能得到月球名称

 $i = 1;
$month = time();
while($i <= 12)
{
    $month_name = date('F', $month);
    echo '<option value="'. $month_name. '">'.$month_name.'</option>';
    $month = strtotime('+1 month', $month);
    $i++;
}

但是我需要得到过去4,5年的月份和年份,任何人都知道如何使用php日期函数或任何其他短期方法。谢谢你

将这样的东西放入函数中:

$start = strtotime('2014-01');
$end = strtotime('2014-12');
$range = array(date('Y-m', $start) => date('Y-m', $start));
while ( $start <= strtotime('-1 month', $end) ) {
    $start = strtotime('+1 month', $start);
    $yearMonth = date('Y-m', $start);
    $range[$yearMonth] = $yearMonth;
}
var_dump($range);

添加

$year_name=date('Y',$month);

以及$month_name,并相应地调整您的selectoption

或者,你可以做

$month_name = date('F/Y', $month);

此外,4.5年是4*12+6=54个月,因此while($i <= 54)