我有这件哦代码:
<?php
$levels = array( "0" => "Super User", "1" => "Administrator", "10" => "10", "20" => 20, "30" => "30", "40" => "40", "50" => "50", "99" => "99 News homepage" );
?>
<select name="level" id="modify_modal_level">
@foreach( $levels as $key => $val )
<option value="{{ $key }}" <?php echo $selected==$key ? 'selected="selected"': ""?>>{{ $val }}</option>
@endforeach
</select>
为什么foreach里面的$ key返回数组的INDEX?
示例:
@foreach( $levels as $key => $val )
{{ $key }},
@endforeach
打印出来: 1,2,3,4,5,6,7,8,
代替: &#39; 0&#39;&#39; 1&#39;&#39; 10&#39;&#39; 20&#39;&#39; 30&#39;&#39; 40& #39;,&#39; 50&#39;&#39; 99&#39;
但$ key变量中的foreach循环必须返回关联数组的键值,而不是键索引!
我的选择结果:
<select name="level" id="modify_modal_level">
<option value="1">Super User</option>
<option value="2">Administrator</option>
<option value="3">10</option>
...
<option value="8">99 News homepage</option>
</select>
而不是:
<select name="level" id="modify_modal_level">
<option value="0">Super User</option>
<option value="1">Administrator</option>
<option value="10">10</option>
...
<option value="99">99 News homepage</option>
</select>
谢谢!
答案 0 :(得分:0)
您的代码现在可以正常运行;您是否确定$levels
正确生成,因为您在此处显示它?
<强>控制器强>
$levels = [
0 => "Super User",
1 => "Administrator",
10 => 10,
20 => 20,
30 => 30,
40 => 40,
50 => 50,
99 => "99 News homepage",
];
return view('yourview', [
'levels' => $levels,
'selected' => '99'
]);
<强> yourview.blade.php 强>
<select name="level" id="modify_modal_level">
@foreach ($levels as $key => $value)
<option value="{{ $key }}" @if ($selected == $key) selected @endif>{{ $value }}</option>
@endforeach
{{-- $key will be 0, 1, 10, 20, 30, 40, 50, 99 --}}
{{-- $value will be "Super User", "Administrator", 10, 20, 30, 40, 50, "99 News homepage" --}}
</select>
请注意,我还更新了使用@if
Blade语法,因为它更清晰,更易于阅读。
访问视图时,我会收到此消息: