Laravel对'A%'的集合过滤器,就像我们对'A%'这样的地方一样

fhity93d  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(95)

我想过滤一堆以字符开头后跟通配符 * 的名称

查询

我可以通过查询来实现这一点,例如:第一个月
由于我缓存了模态::类,所以我不想重复它,而是使用filter()其他可以帮助我获得预期结果的东西

集合过滤器()

return $collection->filter(function ($q) use ($name) {
    return false !== stripos($q['name'], $name); // this returns all the names that contains $name character
});

字符串
我想实现的是filter()名称以特定字符开头,然后是'%' --$name . '%'例如。'A%'
下面是我经历的几个SO链接
Collection Where LIKE Laravel 5.4
Laravel 5.5 Collection where like

yks3o0rb

yks3o0rb1#

你可以使用Str::startsWith助手。

use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

字符串
应用到您的代码,它应该是

use Illuminate\Support\Str;

return $collection->filter(function ($q) use ($name) {
    return Str::startsWith($q['name'], $name);
});


对于laravel 5.7之前的版本,请使用starts_with助手。

$result = starts_with('This is my name', 'This');

// true

yhqotfr8

yhqotfr82#

考虑这个集合:

$certs = collect([[
    'id' => 1,
    'name' => 'Master'
], [
    'id' => 2,
    'name' => 'Doctor'
]]);

字符串
下面是一个Collection过滤记录的例子,它的工作原理与where like sql query statement特性完全相同。

$collectionWhereLike = function ($collection, $key, $term) {
    $filtered = $collection->filter(fn ($item) => Str::contains($item[$key], $term));
    $reIndexed = array_values($filtered->toArray());
    return collect($reIndexed);
};


用法

$filtered = $collectionWhereLike($certs, 'name', $term);


示例

// when
$term = '';
// ouputs
"Illuminate\Support\Collection":[
    {"id":1,"name":"Master"},
    {"id":2,"name":"Doctor"}
]
// when
$term = 'to';
// ouputs
"Illuminate\Support\Collection":[
    {"id":2,"name":"Doctor"}
]

相关问题