好的,所以我试图让表单下拉菜单自动选择当前日期而不需要太多的javascript编码,所以我得到了下面的代码(它不会自动选择,但它确实包括当前日期作为第一个选项)。这一年并没有像预期的那样首次出现。我做了相同的日和月,这两个工作完美,但当我有相同的代码,除了几天/几个月(mday和mon括号内),第一年的选择没有出现。我猜这个问题是[$ t ['year']]的两个实例中的部分。其余的代码运行正常,但我只是把它包括在内,以防我错过了一些事情(我也尝试用最后两个数字代替所有年份,但结果相同)。
<?php
$t = getdate(time());
$year = array(1 =>'2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030');
echo '  Year <select name="year" >';
echo '<option value="\" . $t[\'year\'] . \"">' . $year[$t['year']] . '</option>';
foreach( $year as $key => $value ) {
echo "<option value = \"$key\">$value</option>";
}
echo '</select>'; ?>
答案 0 :(得分:3)
使用date('Y')
。
http://php.net/manual/en/function.date.php
<?php
$t = getdate(time());
$year = array('2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030');
echo '  Year <select name="year" >'."\n";
echo '<option value="' . array_search(date('Y'),$year) . '">' . date('Y') . '</option>'."\n";
foreach( $year as $key => $value ) {
echo "<option value = \"$key\">$value</option>\n";
}
echo '</select>'."\n";
?>
这也只会选择select
中的一个值,因此您不需要两个:
<?php
$t = getdate(time());
$year = array('2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030');
$c_year = date('Y');
echo '  Year <select name="year" >'."\n";
foreach( $year as $key => $value ) {
echo "<option".($c_year == $value?' selected="true"':'')." value = \"$key\">$value</option>\n";
}
echo '</select>'."\n";
?>
答案 1 :(得分:2)
$years = range(2000, 2030);
$cur_year = date('Y');
echo '<select name="year">';
foreach($years as $year)
if($year == $cur_year)
echo "<option selected>$year</option>";
else
echo "<option>$year</option>";
echo '</select>';