我正在搜索一个集合,希望这个搜索不区分大小写,或者至少将集合的值更改为小写。我该如何做?
$value = strtolower($value);
$collection = $collection->where($attribute, $value);
$value是小写的,而集合中的内容不是,所以没有匹配项。
你可以使用 filter()
方法和一个回调函数来实现你想要的功能:
$collection = $collection->filter(function ($item) use ($attribute, $value) {
return strtolower($item[$attribute]) == strtolower($value);
});
$value = strtolower($value);
$collection = $collection
->map(function ($item) use ($attribute) {
$item->{$attribute} = strtolower($item->{$attribute});
return $item;
})
->where($attribute, $value);
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Collection::macro('locate', function (string $attribute, string $value) {
return $this->filter(function ($item) use ($attribute, $value) {
return strtolower($item[$attribute]) == strtolower($value);
});
});
}
}
使用方法如下:
$collect->locate("sku", "KFALTJK2321")->first()
我创建了一个集合宏,用于执行不区分大小写的搜索。
下面的版本将获取与不区分大小写项匹配的集合中的第一项。
将此添加到您的服务提供者:
Collection::macro('insensitiveFirstWhere', function ($key, $value = null) {
if (func_num_args() === 1) {
$value = true;
}
else if (is_string($value)) {
$value = mb_strtolower($value);
}
return $this->first(function ($item) use ($key, $value) {
$itemValue = $item->{$key};
if (is_string($itemValue)) {
$itemValue = mb_strtolower($itemValue);
}
return $itemValue == $value;
});
});
使用它,只需调用:
$collection = collect(['name' => 'John'], ['name' => 'Bobby']);
// will return John, as 'John' == 'john'
$collection->insensitiveFirstWhere('name', 'john');