【问题标题】:Looping through collections -Laravel循环遍历集合-Laravel
【发布时间】:2018-06-16 00:45:30
【问题描述】:

我试图根据密钥循环遍历一个集合

我在这里尝试完成的是根据我认为的字母表对每家公司进行分组。

我如何循环这个??

$results = $companies->sortBy('name')->groupBy(function ($item, $key) {
                 return substr($item['name'], 0, 1);
        });

       dump($results);

控制器

【问题讨论】:

  • 您的问题与分组或迭代集合有关吗?
  • 以下答案之一是否解决了您的问题?如果是这样,请您将其标记为已接受:) 否则,请您解释您仍然遇到的问题。

标签: php laravel collections laravel-eloquent


【解决方案1】:

作为@msonowal 答案的替代方案,您还可以使用each()

$results->each(function ($collection, $alphabet) {
    dump($alphabet, $collection);
});

但是,如果您要在刀片文件中遍历它们,您可以使用:

@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);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 1970-01-01
      • 2020-09-10
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多