简体   繁体   English

PHP创建从当月开始的选择框

[英]PHP Creating select box starting from current month

I have a select box with the following values ( months of the year ): 我有一个选择框,其中包含以下值(一年中的几个月):

<label for="select_month">Month: </label>
<select id="select_month" name="month">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>

What I would like to achieve is to get with PHP the current month, and make that as default-selected option in my select box. 我想要实现的是使用PHP当前月份,并将其作为我选择框中的默认选择选项。

How can I do that with a clean code? 我怎么能用干净的代码做到这一点?

for ($i = 1; $i <= 12; $i++)
(
    $month = ($i < 10) ? '0'.$i : $i;
    echo '<option value="'.$month.'"';
    if ($i == date("n")) echo ' selected="selected"';
    echo '>'.$month.'</option>';
)

I can't test this as I'm on my phone, but that should do the trick. 我无法测试这个,因为我在手机上,但这应该可以解决问题。

Perhaps something like this? 也许是这样的?

<select name="month">
<?php foreach(range('1', '12') as $m) : ?>
    <option value="<?php echo $m; ?>" <?php if (date('n') == $m) { echo 'selected="selected"'; } ?>>
        <?php echo $m ?>
     </option>
<?php endforeach; ?>
</select>

Here is my two cents: 这是我的两分钱:

<label for="select_month">Month: </label>
<select id="select_month" name="month">

<?php

 for($i = 1; $i <= 12; $i++) {
  $isCurrentMonth = ($i == intVal(date("m"))) ? 'true': 'false';
  echo "<option value=\"$i\" selected=\"$isCurrentMonth\">$i</option>\n";
 }

?>

</select>

Uses a similar structure to Pratt's answer, but uses the double-digit month values (like you had in your example). 使用与Pratt的答案类似的结构,但使用两位数的月份值(就像您在示例中所做的那样)。 It uses date('m') instead of date('n') and since there doesn't appear to be any way to get leading zeros in PHP range, I used an array. 它使用日期('m')而不是日期('n'),因为似乎没有任何方法可以在PHP范围内获得前导零,我使用了一个数组。

<select name="month">
<?php foreach(array('01','02','03','04','05','06','07','08','09','10','11','12') as $m) : ?>
    <option value="<?php echo $m; ?>" <?php if (date('m') == $m) { echo 'selected="selected"'; } ?>>
        <?php echo $m ?>
     </option>
<?php endforeach; ?>
</select>
<option value="01" <?php echo (1 == date("n") ? 'selected="selected"' : ''); ?>>01</option>

这必须针对每个选项进行 - 在这种情况下for循环可能会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM