2

我正在努力成为一个更好的 PHP 编码器。我找到的解决方案有效(如下),但看起来它不是解决这个问题的最佳方法。任何更好的开发人员能否想出一种更好的方法来使用数据库中更普遍可用的数组重新选择多选列表中的项目?感谢您帮助我成为更好的开发人员。

<?php
$optFood = '';
$optMedication = '';
$optVaccinations = '';
$optMedicalServices = '';
$optVaccinations = '';
$optOutdoorHousing = '';
$optOther = '';

$options = explode(",", mysql_result($call, 0, 'assistNeeds'));
foreach($options as $val) {
${"opt".str_replace(' (See Notes)','',str_replace(' ','',$val))} = "selected=\"selected\"";
}
?>

<select name="assistNeeds[]" size="6" multiple class="span2" id="assistNeeds" tabindex="12" title="Select All">                                      
<option <?php echo $optFood ?> value="Food">Food</option>
<option <?php echo $optMedication ?> value="Medication">Medication</option>
<option <?php echo $optMedicalServices ?> value="Medical Services">Medical Services</option>
<option <?php echo $optVaccinations ?> value="Vaccinations">Vaccinations</option>
<option <?php echo $optOutdoorHousing ?> value="Outdoor Housing">Outdoor Housing</option>
<option <?php echo $optOther ?> value="Other (See Notes)">Other (See Notes)</option>
</select>
4

1 回答 1

1

您可以使用 foreach 循环从数组创建选项来简化它$assistNeeds

<select name="assistNeeds[]" size="6" multiple="multiple" class="span2" id="assistNeeds" tabindex="12" title="Select All">
<?php
  $options = explode(",", mysql_result($call, 0, 'assistNeeds'));
  $assistNeeds = array("Food","Medication","Medical Services","Vaccinations","Outdoor Housing","Other (See Notes)");
  foreach($assistNeeds as $option) {
      $selected = (in_array($option, $options)) ? ' selected="selected"' : '';
      echo '<option'.$selected.' value="'.$option.'">'.$option.'</option>';
  }
?>
</select>

这个 phpfiddle - http://phpfiddle.org/main/code/kkb-4q2 -$options = explode(",", "Food,Vaccinations");在示例中使用

于 2013-06-07T22:58:59.757 回答