Looping through collections -Laravel

旧时模样 提交于 2021-02-05 08:58:06

问题


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


回答1:


As an alternative to @msonowal's answer you can also use 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




回答2:


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


来源:https://stackoverflow.com/questions/48126573/looping-through-collections-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!