我需要帮助,因为我有执行代码的问题。在我的数据库中,我存储一个多个选择的多个阵列,具有此格式:[" 5"," 6"," 7"," 8"]我使用json_encode存储我的数组。
我的表单具有选择多个多个(https://www.virtuosoft.eu/code/bootstrap-duallistbox)。
此输入用表的数据填充。所以这是填充的左边的列表。
我想用存储在数据库中的数据填充右侧的列表。为此,我必须将选定的每个选项选择对应。但是我不知道这样做...我认为我使用double foreach具有if条件,但是....
一些代码来解释这一点:
保存所有选项的表:表名:婚礼
字段:id,title
带有选定选项保存的表
表名称:步骤
字段:ID,参与者=>此字段具有weddings.id的数量,例如[" 5"," 6"," 7"," 8"]
为了填写我的选择列表,我要这样做
<select multiple="multiple" id="participants" class="form-control" name="participants[]">
@foreach ($weddings as $wedding)
<option value="{{ $wedding->id }}" >{{ $wedding->title }} </option>
@endforeach
</select>
要从步骤中检索数据
foreach(json_decode($step->participants) as $k => $v){
echo '<option value="'.$v.'" selected>'.$v.'</option>';
}
因为我需要将"选定"放在选项上,所以此一个转到正确的列表。
如何将2个foreach组合到我的步骤表中的"选择"值存储的婚礼表?
?我希望你能理解我。
非常感谢。
ps:我使用laravel
尝试一下,最重要的是理解!
// select all participants
// for example lets say you got this from your database
$data = '["5","7","9","2"]';
// now decode it
$data = json_decode($data);
$weddings = [];
// convert values to integers
foreach($data as $key => $value)
{
$weddings[$key] = (Int) $value;
}
// create select input
$input = '<select>';
foreach($weddings as $id)
{
// lets say you want wedding id 5 to be selected
// all you have to do is add an If statement and that's it !
if($id === 5) {
// this is wedding id 5 !
$input .= '<option value="'.$id.'" selected>'.$id.'</option>';
} else if ($id === 7) {
// do something with wedding id 7 ?
$input .= '<option value="'.$id.'" class="number7">'.$id.'</option>';
} else {
$input .= '<option value="'.$id.'">'.$id.'</option>';
}
}
// close select input tag
$input .= '</select>';
echo $input;
惊人!!!它有效。
,但是我需要更改第二个之后的第一个foreach的关闭,因为如果没有,我只有循环的最后一项。
非常感谢 azjezz 。
有关信息,这是我的工作代码:
<div id="select-participants" class="form-group {{ $errors->has('participants') ? 'has-error' : '' }}">
<label for="participants" class="col-sm-2 control-label">{!! $errors->has('participants') ? '<i class="fa fa-times-circle-o"></i>' : '' !!}Participants</label>
<div class="col-sm-10">
<select multiple="multiple" id="participants" class="form-control" name="participants[]">
@php
$export_json_participants = json_decode($preparationStep->participants);
@endphp
@foreach($export_json_participants as $key => $value)
$export_json_participants[$key] = $value;
@foreach ($weddings as $wedding)
<option value="{{ $wedding->id }}" {{ $wedding->id == $export_json_participants[$key] ? 'selected' : '' }}>{{ $wedding->title }}</option>
@endforeach
@endforeach
</select>
@if ($errors->has('participants'))
<span class="help-block">
<strong>{{ $errors->first('participants') }}</strong>
</span>
@endif
</div>
</div>
非常感谢您,没关系,我明白了。: - )