laravel 在foreach中获取对象的位置(索引)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50864982/
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
Getting the position (index) of an object in foreach?
提问by walino
I have a simple foreach block in my view, like below.
在我看来,我有一个简单的 foreach 块,如下所示。
@foreach ($teams as $key => $team)
{{ str_ordinal($key + 1) }}
@endforeach
Right now I'm displaying the key, although it isn't exactly accurate. Here's an image:
现在我正在显示密钥,尽管它并不完全准确。这是一张图片:
How can I display the actual position of the current iteration? I order by my teams
collection but I'm not sure how I get the position of the current interation in that loop?
如何显示当前迭代的实际位置?我按我的teams
收藏订购,但我不确定如何获得该循环中当前交互的位置?
回答by alynurly
You can use $loop->index
to get the index
您可以使用$loop->index
来获取索引
回答by u_mulder
You can apply array_values
to your data before passing to template:
您可以array_values
在传递给模板之前应用到您的数据:
array_values($teams);
Or, according to this https://laravel.com/docs/5.6/blade#the-loop-variable, you can use special $loop
variable. I suppose you need $loop->iteration
property (it starts with 1
) or $loop->index
(starts with 0
):
或者,根据此https://laravel.com/docs/5.6/blade#the-loop-variable,您可以使用特殊$loop
变量。我想您需要$loop->iteration
财产(以 开头1
)或$loop->index
(以 开头0
):
@foreach ($teams as $key => $team)
{{ $loop->iteration }}
@endforeach
回答by Mr Glass
Use a for
loop instead of a foreach
. You will get them in order.
使用for
循环而不是foreach
. 你会按顺序得到它们。
$count = count($teams) ;
for($i=1;$i<=$count;$i++) {
// your code here using $i as the position
}