场景
laravel5.5对collection进行了大力的加持,时刻保持自己获取到的数据的类型是collection 而非array是很明智的选择
所以Collection each 函数就会经常用到了The each method iterates over the items in the collection and passes each item to a callback:
If you would like to stop iterating through the items, you may return false from your callback:官方文档对它的介绍是很简单的,源码呢?也是很简单的
解析
- 外层包裹的是foreach
内层告诉我们如果 callback function返回false 则循环break; 这个本质上就是一个带有break功能的array_walk
- 下面简单使用
/**
* 当前数据中是否需要添加unread的类
* @param array $item_messages
* @return boolean
*/
protected function unreadClass($item_messages)
{
$unread_class = false;
$item_messages->each(function ($item) use (&$unread_class) {
if ($item->user_id != $item->from_user_id && $item->is_read === 'F') {
$unread_class = true;
return false;
}
});
return $unread_class;
}
源码
/**
* Execute a callback over each item.
*
* @param callable $callback
* @return $this
*/
public function each(callable $callback)
{
foreach ($this->items as $key => $item) {
if ($callback($item, $key) === false) {
break;
}
}
return $this;
}