从PHP中的选择框中删除重复的选项

时间:2014-08-12 07:55:22

标签: php html arrays foreach

我想根据$chosen数组中的元素数生成选择框,每个框都有默认的选定选项。第一个是A,第二个是D。以下代码几乎没问题,除了我想删除重复的选项。这是输出:

<select>
   <option>Select</option>
   <option value="A" selected="selected">A</option>
   <option value="A">A</option>
   <option value="B">B</option>
   <option value="C">C</option>
   <option value="D">D</option>
   <option value="E">E</option>
</select>

<select>
 <option>Select</option>
 <option value="D" selected="selected">D</option>
 <option value="A">A</option>
 <option value="B">B</option>
 <option value="C">C</option>
 <option value="D">D</option>
 <option value="E">E</option>
</select>

我尝试array_mergearray_unique合并$options$chosen foreach($options as $option)之前,但它无效。谁有人建议解决方案?

<?php

$options = array("A","B","C","D","E");
$chosens = array("A","D");


foreach($chosens as $chosen)
{
  print "<select><option>Select</option>";

  if(in_array($chosen,$options))
  {
    print "<option value='".$chosen."' selected='selected'>$chosen</option>";
  }

 /* $options = array_unique(array_merge($chosen,$options)); */

    foreach($options as $option)
    {
      print "<option value='".$option."'>$option</option>";

    }

  print "</select>";
}

?>*

1 个答案:

答案 0 :(得分:1)

实际上,只是一个简单的if条件就足够了。像这样:

<?php

$options = array("A","B","C","D","E");
$chosens = array("A","D");

?>

<?php foreach($chosens as $chosen): ?>
    <select name="">
    <?php foreach($options as $option): ?>
        <option value="<?php echo $option; ?>" <?php echo ($option == $chosen) ? 'selected' : ''; ?>><?php echo $option; ?></option>
    <?php endforeach; ?>
    </select><br/>
<?php endforeach; ?>