编程

Laravel Collection 新增的 select 方法

264 2024-06-08 02:27:00

还记得 Laravel Collection 中 only 方法吗,它允许你从集合中检索项目子集,
例如,如果有一个这样的数据数组。

$collection = collect([
    'name' => 'Amit',
    'age' => 30,
    'city' => 'Surat',
    'country' => 'India'
]);

你可以使用 only 从集合中检索子集,如下所示。

$filtered = $collection->only(['name', 'age']);
// ['name' => 'Amit', 'age' => 30]

在 Laravel Collection 中有一个名为 select 的新方法,它的作用与 only 方法相同,但用于数组的数组
例如,有一个这样的数组组成的数组。

$collection = collect([
    ['name' => 'Amit', 'age' => 30, 'country' => 'India'],
    ['name' => 'John', 'age' => 25, 'country' => 'USA'],
    ['name' => 'Jane', 'age' => 35, 'country' => 'UK'],
]);

现在,如果想从集合中检索项目的子集,例如名称(name)和国家(country),可以使用这样的 select 方法。

$filtered = $collection->select(['name', 'country']);

/*
[
    ['name' => 'Amit', 'country' => 'India'],
    ['name' => 'John', 'country' => 'USA'],
    ['name' => 'Jane', 'country' => 'UK'],
]
*/