2013-08-01 21 views
0

我在本月的最后一天持续出现问题,除此之外,此代码可以正常显示从当前月份开始的所有12个月。在本月的最后一天,我得到了几个月的重复,其他人根本没有出现。任何帮助,将不胜感激。谢谢。PHP下拉选择功能动态创建月份

<select id="month" name="month"> 


<?php 

//lists months 

    for ($i = 0; $i <= 11; ++$i) 
     { 
      $time = strtotime(sprintf('+%d months', $i)); 
      $value = date('m', $time); 
      $label = date('F', $time); 

//if month is set stay on that month 

      if($month==$value) 
       { printf('<option value="%s" selected="selected">%s</option>' , $value, $label); 
       } 
      else 
       {printf('<option value="%s">%s</option>', $value, $label);} 
     } 

?> 

//first month shows instead of blank 

    $("#target option:first") 

</select> 
+0

你在哪里设置$ month的值? – Maximus2012

+0

另外,您是否可以检查您是否在不同情况下为$ time获得正确的值? – Maximus2012

回答

1

您可能运行到一个问题,即从目前的日X个月后,每月跳过。 而不是

strtotime(sprintf('+%d months', $i)); 

尝试使用

strtotime(sprintf('first day of +%d month', $i)); 
0
<?php 

    function months($selctedMonth='january'){ 

     $months='<select name="month" size="1">'; 
     for ($i = 12; $i > 0; $i--) { 
      $time = strtotime(sprintf('-%d months', $i)); 
      $label = date('F', $time); 
      $selctedM = strtolower($selctedMonth) == strtolower($label) ? 'selected' : ''; 
      $months.="<option value='$label' $selctedM >$label</option>"; 
     } 
     $months.="</select>"; 
     return $months; 
    } 

    echo months(); 


?> 

默认情况下,作为选择的月份将被显示。

如果你写<?php echo months('march'); ?>则默认选择march