Laravel 5.2 foreach 键返回索引中的关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34907047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.2 foreach associative array in key return index
提问by Robbè Meulz
I have this piece oh code:
我有这段哦代码:
<?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>
Why the $key inside foreach return the INDEX of array?
为什么foreach里面的$key返回数组的INDEX?
example:
例子:
@foreach( $levels as $key => $val )
{{ $key }},
@endforeach
prints out: 1,2,3,4,5,6,7,8,
打印出来:1,2,3,4,5,6,7,8,
instead of: '0','1','10','20','30','40','50','99'
而不是:'0'、'1'、'10'、'20'、'30'、'40'、'50'、'99'
but the foreach loop in the $key variable MUST return the key value of the associative array, not the key index!
但是 $key 变量中的 foreach 循环必须返回关联数组的键值,而不是键索引!
my select results:
我选择的结果:
<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>
instead of:
代替:
<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>
Thanks!!
谢谢!!
回答by camelCase
Your code will work as you have it now; are you certain that $levels
is correctly generated as you're showing it here?
您的代码将像您现在拥有的那样工作;您确定$levels
在此处显示它是正确生成的吗?
Controller
控制器
$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
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>
Note that I also updated to use @if
Blade syntax since it's much cleaner and easier to read.
请注意,我还更新为使用@if
Blade 语法,因为它更清晰、更易于阅读。
When accessing the view, I get this returned:
访问视图时,我得到了这个返回: