Might not be a question specific to Eloquent collections, but it just hit me while working with them. Let's just assume we have a $collection object which is an instance of Illuminate\Support\Collection.

Now if we want to iterate over it, what are the pros and cons of using each() with a closure versus a regular foreach. Are there any?

foreach ($collection as $item) {
    // Some code
}

versus

$collection->each(function ($item) {
    // Some code
});

推荐答案

A foreach statement should be used as a sort of a way to cycle through a collection and perform some sort of logic on it. If what is in it effects other things in the program, then use this loop.

The .each method uses array_map to cycle through each of the objects in the collection and perform a closure on each one. It then returns the resulting array. That is the key! .each should be used if you want to change the collection in some way. Maybe it's an array of cars and you want to make the model upper case or lower case. You would just pass a closure to the .each method that takes the object and calls strtoupper() on the model of each Car object. It then returns the collection with the changes that have been made.

故事的寓意是:使用.each方法以某种方式更改数组中的每个项目;使用foreach循环使用每个对象影响程序的其他部分(使用一些逻辑语句).

更新版(2015年06月7日)

如此Eloquent 地陈述(看到我在那里做了什么吗?)下面,上述答案略有偏差.使用array_map.each方法实际上从未使用过array_map调用的输出.因此,array_map创建的新数组不会保存在Collection上.要更改它,最好使用.map方法,该方法也存在于Collection对象上.

使用foreach语句对它们进行迭代更有意义,因为除非确保使用use语句,否则将无法访问闭包之外的变量,这在我看来很尴尬.

最初编写上述答案时的实现可以是found here.

.each in Laravel 5.1

The new .each that they are talking about below no longer uses array_map. It simply iterates through each item in the collection and calls the passed in $callback, passing it the item and its key in the array. Functionally, it seems to work the same. I believe using a foreach loop would make more sense when reading the code. However, I see the benefits of using .each because it allows you to chain methods together if that tickles your fancy. It also allows you to return false from the callback to leave the loop early if your business logic demands you to be able to.

有关新实现的更多信息,请查看the source code.

Laravel相关问答推荐

如何让 Laravel 的 Collection 表现得像一个流?

如何获取多态多对多关系子查询的自动 id 列名?

找不到 Laravel 5 类日志(log)

Laravel 5 Eloquent 范围连接并 Select 特定列

判断 Laravel 模型表中是否存在列,然后应用条件

如何使用 Eloquent Laravel 更新集合

Laravel 5.4 LengthAwarePaginator

laravel 5中的配置缓存导致找不到视图

Laravel 5 - Php artisan语法错误

使用数据库中的值进行动态邮件配置 [Laravel]

如何在 Laravel 5 中按键获取所有缓存项目的列表?

Laravel:命令未找到

Laravel Eloquent ORM 复制

Laravel 5 Carbon 全局语言环境

如何在 Laravel 4 中组织不同版本的 REST API 控制器?

找不到框laravel/homestead

在我的编辑器中管理上传文件的最佳方式?

如何使用 Laravel 迁移在 Mysql 列中添加注释

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500

在 Laravel 中翻译特定语言