Laravel 8 firstWhere() {#collection-method}

2021-07-19 09:35 更新

firstWhere 方法返回集合中含有指定鍵 / 值對(duì)的第一個(gè)元素:

$collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('name', 'Linda');

// ['name' => 'Linda', 'age' => 14]

你也可以使用運(yùn)算符來(lái)調(diào)用 firstWhere 方法:

$collection->firstWhere('age', '>=', 18);

// ['name' => 'Diego', 'age' => 23]

where 方法一樣,你可以將一個(gè)參數(shù)傳遞給 firstWhere 方法。在這種情況下, firstWhere 方法將返回指定鍵的值為「真」的第一個(gè)集合項(xiàng):

$collection->firstWhere('age');

// ['name' => 'Linda', 'age' => 14]


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)