【问题标题】:PHP dropdown select function to dynamically create monthsPHP下拉选择函数动态创建月份
【发布时间】:2013-08-01 16:56:19
【问题描述】:

我在该月的最后一天一直遇到问题,除了此代码可以正常显示从当前月份开始的所有 12 个月。在这个月的最后一天,我得到了一些月份的副本,而其他月份则根本没有显示。任何帮助,将不胜感激。谢谢。

<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>

【问题讨论】:

  • 你在哪里设置 $month 的值?
  • 另外,你能检查一下你在不同情况下得到的 $time 值是否正确吗?

标签: php date select drop-down-menu monthcalendar


【解决方案1】:

您可能会遇到一个问题,即从 X 个月后的今天开始跳过一个月。 而不是

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

尝试使用

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

【讨论】:

    【解决方案2】:
    <?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(); 
    
    
    ?>
    

    默认情况下,一月将显示为选中状态。

    如果你写&lt;?php echo months('march'); ?&gt;,那么march将默认被选中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2014-06-09
      • 2013-07-09
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多