阅读(4277) (6)

Laravel 8 countBy() {#collection-method}

2021-07-01 14:28:54 更新

countBy 方法计算集合中每个值的出现次数。默认情况下,该方法计算每个元素的出现次数:

$collection = collect([1, 2, 2, 2, 3]);

$counted = $collection->countBy();

$counted->all();

// [1 => 1, 2 => 3, 3 => 1]

但是,你也可以向 countBy 传递一个回调函数来计算自定义的值出现的次数:

$collection = collect(['[email protected]', '[email protected]', '[email protected]']);

$counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
});

$counted->all();

// ['gmail.com' => 2, 'yahoo.com' => 1]