两者都是对集合进行遍历处理
Map()
/**
* Run a map over each of the items.
*
* @param callable $callback
* @return \Illuminate\Support\Collection|static
*/
public function map(callable $callback)
{
$result = parent::map($callback);
return $result->contains(function ($item) {
return ! $item instanceof Model;
}) ? $result->toBase() : $result;
}
// 其中 parent::map($callback);
/**
* Run a map over each of the items.
*
* @param callable $callback
* @return static
*/
public function map(callable $callback)
{
$keys = array_keys($this->items);
$items = array_map($callback, $this->items, $keys);
return new static(array_combine($keys, $items));
}
// Creates an array by using one array for keys and another for its values
function array_combine(array $keys, array $values) { }
从中可以看出,map返回一个新的集合,其中的值为回调函数处理过后的数据
Each()
/**
* Execute a callback over each item.
*
* @param callable $callback
* @return $this
*/
public function each(callable $callback)
{
foreach ($this as $key => $item) {
if ($callback($item, $key) === false) {
break;
}
}
return $this;
}
而each返回的还是原集合,只是以遍历的形式对原集合进行回调函数中的处理,
由上可以看出,each()通常用在循环操作,map()用在集合数据格式转换