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.