Php 不要在我的下拉框中显示重复的值
我需要一些逻辑方面的帮助。我正在选择框中填充数据库中的值 如果存在,我将回显该值,否则我将显示默认选项 现在,例如,如果数据库中的值是newjersey,我不想在下拉框中第二次显示newjersey。我该怎么做Php 不要在我的下拉框中显示重复的值,php,javascript,jquery,html,forms,Php,Javascript,Jquery,Html,Forms,我需要一些逻辑方面的帮助。我正在选择框中填充数据库中的值 如果存在,我将回显该值,否则我将显示默认选项 现在,例如,如果数据库中的值是newjersey,我不想在下拉框中第二次显示newjersey。我该怎么做 <select name="location" class="field" > <option value="<?php if(!empty($get_location)){ echo $get_location; } ?
<select name="location" class="field" >
<option value="<?php if(!empty($get_location)){ echo $get_location; } ?>"><?php if(!empty($get_location)){ echo $get_location; }?></option>
<option value="New Jersey">New Jersey</option>
<option value="New York">New York</option>
<option value="California">California</option>
</select>
您可以在每个选项字段中使用if语句,并检查数据库中的值是否与选项字段的值匹配,如果匹配,则将“selected=\“true\”
返回到选项字段
有关代码示例,请参见我对该问题的回答:
如果只希望显示数据库值:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
$html .= '<option id="'.$id.'">'.$option.'</option>';
}
echo $html.'</select>';
?>
如果希望数据库值发生特殊情况,但仍然加载默认值:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
// Compare against your full list of locations
// As an example:
$locations = array(1=>'New Jersey',2=>'Los Angeles',3=>'California',4=>'London');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
if(array_key_exists($id,$locations))
{
// Enter your magic
}
}
echo $html.'</select>';
?>
我会稍微更改您的php代码以添加默认值,然后您可以使用jQuery过滤和删除重复项。如果有很多选择,这可能不是最好的解决方案 php
<select name="location" class="field">
<?php if(!empty($get_location)): ?>
<option value="<?php echo $get_location; ?>">
<?php echo $get_location; ?>
</option>
<?php else: ?>
// Defaults
<?php endif; ?>
</select>
在对数据库的一个请求中获取您的位置,将它们与默认值一起添加到数组中,如果只有一个位置执行以下操作,如果多个位置将它们解析为一个数组并将它们与默认值合并,则执行一个数组_unique以消除重复项并在循环中输出该数组
<select name="location" class="field">
<?php
$output = array(1=>'New Jersey', 2=>'New York', 3=>'California', 4=>$get_location);
$options = array_unique($output);
foreach($options as $key => $value) {
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
</select>
New Jersey、New York和California是默认设置?另外,请看一下使用模板引擎(我习惯了,但还有很多其他的()),这将简化开发PHP网页的过程感谢您的帮助……我认为Marc的答案是我正在寻找的快速解决方案!
<select name="location" class="field">
<?php
$output = array(1=>'New Jersey', 2=>'New York', 3=>'California', 4=>$get_location);
$options = array_unique($output);
foreach($options as $key => $value) {
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
</select>