camillebaronnet/

collection

v0.4.0 2022-04-15 18:23 UTC

This package is auto-updated.

Last update: 2024-09-16 00:21:51 UTC


README

Collection 提供了一个基于 map/reduce/filter 原则的强大数据处理系统。得益于 PHP 生成器和不可变性,它允许尽可能晚地计算数据,同时保持内存。

安装

composer require camillebaronnet/collection

如何使用

public Collection::__construct(...$elements)
public Collection::__construct(\Traversable|array $elements)

示例

$collection = (new Collection('foo', 'bar'))
    ->map(fn($word) => 'hello '.$word)
    ->map(fn($word) => strtoupper($word))
;

// The data is computed only here
var_dump($collection->toArray()); 
array(2) {
  [0]=>
  string(9) "HELLO FOO"
  [1]=>
  string(9) "HELLO BAR"
}

基本操作

注意:只要使用 map/filter 操作,就不会执行或存储在内存中。如果您决定执行多个 reduce 或迭代操作,请首先使用 get() 来缓冲之前的操作。

映射

map() 函数遍历每个元素并应用用户提供的转换函数。

map(fn($element) => /* ... */);

示例

(new Collection(10, 50, 100))
    ->map(fn($element) => $element * 2)
    ->toArray()
;

// [20, 100, 200]

筛选

filter() 方法使用提供的函数实现测试元素,以通过测试。

filter(fn ($element) => /* ... */);

示例

(new Collection(10, 50, 100))
    ->filter(fn($element) => $element > 20)
    ->toArray()
;
// [50, 100]

减少

reduce() 方法在用户提供的每个元素上执行减少函数,每次迭代的每个迭代结果传递给下一次迭代。

reduce(fn($carry, $currentValue, $currentKey) => /* ... */, $initial);

示例

(new Collection(10, 50, 100))
    ->reduce(fn($carry, $current) => $carry + $current)
;
// 160

按组分组

groupBy() 方法返回一个包含 CollectionGroup 的 Collection。CollectionGroup 是一个添加了 key 属性的简单集合。

groupBy(fn ($element) => /* ...  */);

示例

$result = (new Collection([
        ['key1' => 'foo', 'key2' => 10],
        ['key1' => 'bar', 'key2' => 11],
        ['key1' => 'foo', 'key2' => 12],
        ['key1' => 'bar', 'key2' => 14],
    ]))
    ->groupBy(fn($x) => $x['key1'])
    ->toArray() // [CollectionGroup, CollectionGroup]
;

$result[0]->key; // 'foo'
$result[0]->toArray(); // [['key1' => 'foo', 'key2' => 10],['key1' => 'foo', 'key2' => 12],]