我在本月的最后一天仍然遇到问题,除此之外,此代码可以正常显示从当月开始的所有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>
答案 0 :(得分:1)
您可能遇到了一个问题,从X个月后的当天开始跳过一个月。 而不是
strtotime(sprintf('+%d months', $i));
尝试使用
strtotime(sprintf('first day of +%d month', $i));
答案 1 :(得分: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();
?>
默认情况下,1月将显示为已选中。
如果您写<?php echo months('march'); ?>
,则默认会选择march
。