Laravel 8 reduce() {#collection-method}

2021-07-02 18:06 更新

reduce 方法將每次迭代的結(jié)果傳遞給下一次迭代直到集合減少為單個(gè)值:

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

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});

// 6 

第一次迭代時(shí) $carry 的數(shù)值為 null; 你也可以通過傳入第二個(gè)參數(shù)到 reduce 來指定它的初始值:

$collection->reduce(function ($carry, $item) {
    return $carry + $item;
}, 4);

// 10 


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)