我有以下代码可以生成一个选择表单,其中包含学年作为选项,例如2010-2011,2011-2012等。
但是,出于某种原因,它产生的选择表格只是增加第一年,而第二年则停留在最后一个数组值,例如2010-2020,2011-2020,2012-2020等。
有人可以帮我理解为什么吗?谢谢!
这是我的代码:
/*
* This function returns the HTML code necessary to be echoed out to produce
* a drop-down box input form for a range of 15 years with the current year selected.
*
* $name $name is the variable string for the drop-down select form's identifying name
* $prepopulated_info $prepopulated_info is the year that is to be prepopulated. The
* range of years is populated based on what this number is.
*/
function schoolYearSelectFormGenerator($name, $prepopulated_info) {
// The current year is the already selected default pre-populated year
if($prepopulated_info == 'Y')
$selected = date($prepopulated_info);
else
$selected = $prepopulated_info;
// r is for range of choices
$r = range(date('Y') - RANGE_OF_YEARS, date('Y') + RANGE_OF_YEARS);
//create the HTML select
$string = '<select name="' . $name . '" id="year" class="form-control">';
$i = 0;
$yearPlusOne = array();
foreach($r as $year)
{
$yearPlusOne[$i] = $year + 1;
$string .= "<option value=\"$year - $yearPlusOne[$i]\" class='normal_select'";
$string .= ($year - $yearPlusOne[$i] = $selected) ? ' selected="selected"' : '';
$string .= ">$year - $yearPlusOne[$i]</option>\n";
$i++;
}
$string .= '</select>';
return $string;
}
答案 0 :(得分:3)
修复此部分:
$string .= ($year - $yearPlusOne[$i] = $selected) ? ' selected="selected"' : '';
到
$string .= ($year - $yearPlusOne[$i] == $selected) ? ' selected="selected"' : '';
// ^== here.
因为$year - $yearPlusOne[$i] = $selected
评估并覆盖了您的$yearPlusOne[$i]
值。
答案 1 :(得分:0)
将底部附近的循环修改为:
foreach($r as $year)
{
$yearPlusOne[$i] = $year + 10;
$string .= "<option value=\"$year - $yearPlusOne[$i]\" class='normal_select'";
$string .= ($year - $yearPlusOne[$i] = $selected) ? ' selected="selected"' : '';
$string .= ">$year - $yearPlusOne[$i]</option>\n";
$i++;
}