使用 PHP 填充带有年份的选择框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7083123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate a Select Box with Years using PHP
提问by Abishek
I would like to fill a select box with year starting from 1950 to the current year. How can I achieve this using PHP? I would not like to use JavaScript for this.
我想用从 1950 年到当年的年份填充选择框。如何使用 PHP 实现这一目标?我不想为此使用 JavaScript。
<select><?php
$currentYear = date('Y');
foreach (range(1950, $currentYear) as $value) {
echo "< option>" . $value . "</option > ";
}
?>
</select>
回答by Chris Baker
Use range
to create an array containing all the required years, loop that array and print an option
for each of the values.
使用range
创建一个包含所有需要几年的数组,循环数组并打印option
每个值。
You can use date('Y')
to figure out the current year.
您可以使用date('Y')
来计算当前年份。
// use this to set an option as selected (ie you are pulling existing values out of the database)
$already_selected_value = 1984;
$earliest_year = 1950;
print '<select name="some_field">';
foreach (range(date('Y'), $earliest_year) as $x) {
print '<option value="'.$x.'"'.($x === $already_selected_value ? ' selected="selected"' : '').'>'.$x.'</option>';
}
print '</select>';
Try it here: http://codepad.viper-7.com/Pw3U4O
在这里试试:http: //codepad.viper-7.com/Pw3U4O
Documentation
文档
回答by sn0ep
<select name="select">
<?php
for($i = 1950 ; $i < date('Y'); $i++){
echo "<option>$i</option>";
}
?>
</select>
Something like this?
像这样的东西?
回答by Phill Pafford
<?php
$starting_year = 1950;
$ending_year = 2011;
for($starting_year; $starting_year <= $ending_year; $starting_year++) {
$years[] = '<option value="'.$starting_year.'">'.$starting_year.'</option>';
}
?>
<select>
<?php echo implode("\n\r", $years); ?>
</select>
Option #2:
选项#2:
<select>
<?php
foreach(range(1950, (int)date("Y")) as $year) {
echo "\t<option value='".$year."'>".$year."</option>\n\r";
}
?>
</select>