我有<select>
个显示年份。
我想从数据库中检查注册年份。
这是图片。
然后这是我在<select>
中的代码
<select class="form-control select search-input-select col-lg-9 required_fields yearSelection registered_year" name="registered_year" style="border-color:red;">
<?php
// Sets the top option to be the current year. (IE. the option that is chosen by default).
$currently_selected = date('Y');
// Year to start available options at
$earliest_year = 2018;
// Set your latest year you want in the range, in this case we use PHP to just set it to the current year.
$latest_year = date('Y');
echo '<option style="text-color:red;" selected disabled value>Select Year</option>';
foreach ( range( $latest_year, $earliest_year ) as $i )
{
foreach($year_reg as $year)
{
$reg = date("Y", strtotime($year->date_created));
if($reg == $i){
echo '<option style="color:red;" value="'.$i.'"'.($i === $currently_selected ? ' selected="selected"' : '').' disabled>'.$i.'</option>';
} else {
echo '<option value="'.$i.'"'.($i === $currently_selected ? ' selected="selected"' : '').' >'.$i.'</option>';
}
}
}
?>
</select>
因此,当数据库中的年份与最早的年份(最近的年份)匹配时,它将变为disabled
,颜色为红色。
它显示2019(w/ red text), 2019, 2018, 2018(w/ red text)
现在我的问题是它显示多个数据。 似乎是什么问题?
答案 0 :(得分:0)
问题是由于内部循环。
请尝试以下代码。我刚刚创建了一个数组来存储来自数据库的年份,然后检查$i
中是否存在$existing_years
并将选项标记为红色。
<?php
$existing_years = [];
foreach ($year_reg as $year) {
$existing_years[] = date("Y", strtotime($year->date_created));
}
?>
然后更改了下拉逻辑。
<select class="form-control select search-input-select col-lg-9 required_fields yearSelection registered_year"
name="registered_year" style="border-color:red;">
<?php
echo '<option style="text-color:red;" selected disabled value>Select Year</option>';
// Sets the top option to be the current year. (IE. the option that is chosen by default).
$currently_selected = date('Y');
// Year to start available options at
$earliest_year = 2018;
// Set your latest year you want in the range, in this case we use PHP to just set it to the current year.
$latest_year = date('Y');
foreach (range($latest_year, $earliest_year) as $i) {
$selected = $i === $currently_selected ? ' selected="selected" ' : '';
$style = (in_array($i, $existing_years)) ? ' style="color:red;" ' : '';
$disabled = (in_array($i, $existing_years)) ? ' disabled ' : '';
echo '<option value="' . $i . '"' . $selected . $style . $disabled . '>' . $i . '</option>';
}
?>
</select>
希望这会有所帮助。