Laravel的集合Collection

陈瀚
2023-12-01

简介

Illuminate\Support\Collection 类提供了一个更具可读性的、更便于处理数组数据的封装。
具体例子看下面的代码。我们使用了 collect 函数从数组中创建新的集合实例,对其中的每个元素运行 strtoupper 函数之后再移除所有的空元素:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
})
->reject(function ($name) {
    return empty($name);
});
结果:
Collection {#515
  #items: array:2 [
    0 => "TAYLOR"
    1 => "ABIGAIL"
  ]
}

创建集合

辅助函数 collect 会为给定的数组返回一个新的 Illuminate\Support\Collection 实例。

$collection = collect([1, 2, 3]);
结果:
Collection {#511
  #items: array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
}

$collection=collect([
            '1'=>1,
            '2'=>2,
            '3'=>3,
            '> 3'=>'> 3',
        ]);
结果:
Collection {#511
  #items: array:4 [
    1 => 1
    2 => 2
    3 => 3
    "> 3" => "> 3"
  ]
}

可用的方法

all

all 方法返回该集合表示的底层 数组:


filter

filter 方法使用给定的回调函数过滤集合的内容,只留下那些通过给定真实测试的内容:

$collection=collect([
            '--' => 0,
            'A' => 1,
            'B' => 2,])->filter()->all();
结果:
array:2 [
  "A" => 1
  "B" => 2
]

first

first 方法返回集合中通过给定真实测试的第一个元素:

$collection = collect([
            ['code' => 0, 'desc' => '0-10'],
            ['code' => 1, 'desc' => '10-50'],
            ['code' => 2, 'desc' => '50-100'],
        ])->where('code','=', 1)->first();
结果:
array:2 [
  "code" => 1
  "desc" => "10-50"
]

implode

implode 方法合并集合中的项目。
其参数取决于集合中项目的类型。如果集合包含数组或对象,你应该传入你希望连接的属性的键,以及你希望放在值之间用来「拼接」的字符串:

$collection = collect(['account_id' => 1, 'product' => 'Desk'])->implode(',');
结果:
"1,Desk"

$collection = collect([
            ['account_id' => 1, 'product' => 'Desk'],
            ['account_id' => 2, 'product' => 'Chair'],
        ])->implode('product',',');
结果:
"Desk,Chair"

$collection=collect([
            1   => 'Sunday',
            2   => 'Monday',
            3   => 'Tuesday',
        ])->keys()->implode(',');
结果:
"1,2,3"

keys

keys 方法返回集合的所有键:

$collection=collect([
            1   => 'Sunday',
            2   => 'Monday',
            3   => 'Tuesday',
        ])->keys();
结果:
Collection {#503
  #items: array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
}
 类似资料: