循环遍历集合-Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48126573/
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
Looping through collections -Laravel
提问by Maxwell
I was trying to loop through a collection based on the key
What I am trying to accomplish here is to group each company based on the alphabet in my view.
我想在这里完成的是根据我认为的字母表对每个公司进行分组。
How do I loop through this??
我如何遍历这个??
$results = $companies->sortBy('name')->groupBy(function ($item, $key) {
return substr($item['name'], 0, 1);
});
dump($results);
Controller
控制器
回答by Rwd
As an alternative to @msonowal's answer you can also use each():
作为@msonowal 答案的替代方案,您还可以使用each():
$results->each(function ($collection, $alphabet) {
dump($alphabet, $collection);
});
However, if you're going to loop through them in a blade file you would use:
但是,如果您要在刀片文件中循环它们,您将使用:
@foreach ($results as $alphabet => $collection)
{!! dump($alphabet, $collection) !!}
@endforeach
回答by msonowal
foreach($results as $alphabet => $collection) {
dump($alphabet, $collection);
}