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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:49:10  来源:igfitidea点击:

Getting the position (index) of an object in foreach?

phplaravel

提问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:

现在我正在显示密钥,尽管它并不完全准确。这是一张图片:

enter image description here

在此处输入图片说明

How can I display the actual position of the current iteration? I order by my teamscollection but I'm not sure how I get the position of the current interation in that loop?

如何显示当前迭代的实际位置?我按我的teams收藏订购,但我不确定如何获得该循环中当前交互的位置?

回答by alynurly

You can use $loop->indexto get the index

您可以使用$loop->index来获取索引

回答by u_mulder

You can apply array_valuesto 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 $loopvariable. I suppose you need $loop->iterationproperty (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 forloop 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 
}