Laravel 8 unique() {#collection-method}

2021-07-19 09:51 更新

unique 方法返回集合中所有唯一項(xiàng)。返回的集合保留著原數(shù)組的鍵,所以在這個(gè)例子中,我們使用 values 方法把鍵重置為連續(xù)編號(hào)的索引:

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

當(dāng)處理嵌套數(shù)組或?qū)ο髸r(shí),你可以指定用于確定唯一性的鍵:

$collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/ 

你也可以通過傳遞自己的回調(diào)函數(shù)來確定元素的唯一性:

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

unique 方法在檢查項(xiàng)目值時(shí)使用「寬松」模式比較,意味著具有整數(shù)值的字符串將被視為等于相同值的整數(shù)。你可以使用 uniqueStrict 方法做「嚴(yán)格」模式比較。

技巧:這個(gè)方法的行為在使用 Eloquent Collections 時(shí)被修改。


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)