循环遍历集合-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

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

Looping through collections -Laravel

phplaravelcollectionslaravel-eloquent

提问by Maxwell

I was trying to loop through a collection based on the keyenter image description here

我试图遍历基于键的集合在此处输入图片说明

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

https://laravel.com/docs/master/blade#loops

https://laravel.com/docs/master/blade#loops

回答by msonowal

foreach($results as $alphabet => $collection) {
  dump($alphabet, $collection);
}