Laravel 8 countBy() {#collection-method}
countBy
方法计算集合中每个值的出现次数。默认情况下,该方法计算每个元素的出现次数:
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]
但是,你也可以向 countBy
传递一个回调函数来计算自定义的值出现的次数:
$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);
$counted = $collection->countBy(function ($email) {
return substr(strrchr($email, "@"), 1);
});
$counted->all();
// ['gmail.com' => 2, 'yahoo.com' => 1]