我没有完全得到下面的代码,但我在下面有一个下拉菜单,我希望它在下面显示这些值:
1
1/2
2
2/3
3
3/4
4
4/5
...
10
现在我也希望能够在提交后保留选项,所以我在下面尝试了这个代码,但问题是它只显示值1/2, 2/3, 3/4, 4/5...
等。
foreach ($years as $year) {
if ($validSubmission && $year == $getduration) {
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year/$nextYear</option>".PHP_EOL;
}else{
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year</option>".PHP_EOL;
}
}else{
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option value='" . $year . "'>$year/$nextYear</option>".PHP_EOL;
}else{
$durationHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL;
}
}
}
下面的origanl代码显示正确的选项,但没有执行$ validSubmission变量,因此在提交页面后它不会保持选项的选择:
foreach ($years as $year) {
$durationHTML .= "<option>$year</option>".PHP_EOL;
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option>$year/$nextYear</option>".PHP_EOL;
}
}
$durationHTML .= '</select>';
以下代码确实会在提交后显示该选项,但不会在值之间显示/
的值:
foreach ($years as $year) {
if ($validSubmission && $year == $getduration) {
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year</option>" . PHP_EOL;
} else {
$durationHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL;
}
}
但是尝试将两种代码结合起来并没有奏效,这就是我遇到的问题
答案 0 :(得分:0)
尝试此修改/简化代码。通过使用ternary comparison - $var = condition ? if_true : if_false
- 来设置selected='selected'
属性,您可以最小化代码(从~17行到~9)。
foreach ($years as $year) {
//Gets the single years - 1,2,3...
$sel =($validSubmission && $year == $getduration)? " selected='selected'": "";
$durationHTML .= "<option value='$year'$sel>$year</option>".PHP_EOL;
//Gets the double years - 1/2,2/3,3/4...
if ($year != $max_year) {
$nextYear = $year + 1;
$sel =($validSubmission && ($year.'/'.$nextYear) == $getduration)? " selected='selected'": "";
$durationHTML .= "<option value='$year/$nextYear'$sel>$year/$nextYear</option>".PHP_EOL;
}
}