我从数据库中提取数据以检索为多选下拉菜单选择的多个选项。我试图将这些值重置为已选中,但只选择其中一个。
我在数据库中的数组:
[data] => SimpleXMLElement Object
(
[term] => LTA
[prevention] => SimpleXMLElement Object
(
[reason] => Array
(
[0] => SimpleXMLElement Object
(
[process] => Recruitment
[processID] => 4
)
[1] => SimpleXMLElement Object
(
[process] => People Management
[processID] => 3
)
[2] => SimpleXMLElement Object
(
[process] => Not Applicable
[processID] => 2
)
)
)
)
这是我用来生成选项的HTML / PHP,并尝试重新选择数组中的选项:
<select name="prevention" id="prevention" class="form-control dd ff" placeholder="Select 1 or more options" multiple="multiple">
<?php foreach($processes->data as $process){
foreach($recordDetails->data->prevention->reason as $is){
if((int)$is->processID == (int)$process->processID){
$isSel = 'selected';
}
else
{
$isSel = '';
}
}
?>
<option value="<?php echo $process->processID . '" '. $isSel . '>'; ?> <?php echo $process->process; ?></option>
<?php } ?>
</select>
答案 0 :(得分:1)
你在内循环中覆盖$isSel
,所以你只能获得最后一次迭代的值。
而是在内循环之外初始化变量:
<select name="prevention" id="prevention" class="form-control dd ff" placeholder="Select 1 or more options" multiple="multiple">
<?php
foreach($processes->data as $process):
$isSel = '';
foreach($recordDetails->data->prevention->reason as $is):
if((int)$is->processID == (int)$process->processID){
$isSel = 'selected';
break;
}
endforeach;
?>
<option value="<?php echo $process->processID . '" '. $isSel . '>'; ?> <?php echo $process->process; ?></option>
<?php
endforeach; ?>
</select>