imran / collection

一个类似 Laravel Collection 的 PHP 类。

1.0.0 2023-03-09 13:35 UTC

This package is auto-updated.

Last update: 2024-09-09 16:47:37 UTC


README

集合包是一个简单的类似 Laravel 的 PHP 类,它提供了一个方便的方式来处理数据数组。这个类提供了许多有用的方法来执行数组上的常见任务。

介绍

Imran\Collection\Collection 类为处理数据数组提供了一个流畅、方便的包装器。例如,查看以下代码。我们将使用 new Collection() 从数组创建一个新的集合实例,对每个元素运行 strtoupper 函数,然后删除所有空元素。

$collection = new Collection(['John', 'doe', null]);
$collection->map(function (string $name) { 
      return strtoupper($name);
  })->reject(function (string $name) {
      return empty($name);
  });

如你所见,Collection 类允许你链式调用其方法来执行底层数组的流畅映射和减少。一般来说,集合是不可变的,这意味着每个 Collection 方法都返回一个新的 Collection 实例。

创建集合

创建集合就像这样

$collection = new Collection([1, 2, 3]);

扩展集合

集合是“可宏化”的,这允许你在运行时向 Collection 类添加额外的方法。Imran\Collection\Collection 类的 macro 方法接受一个闭包,该闭包将在调用宏时执行。宏闭包可以通过 $this 访问集合的其他方法,就像它是集合类的真实方法一样。例如,以下代码向 Collection 类添加了一个 toUpper 方法。

use Imran\Collection\Collection;
Collection::macro('toUpper', function () {
    return $this->map(function (string $value) {
        return strtoupper($value);
    });
});
$collection = new Collection(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']

宏参数

如果需要,你可以定义接受额外参数的宏

use Imran\Collection\Collection;
Collection::macro('toLocale', function (string $locale) { 
    return $this->map(function (string $value) use ($locale) {
        return getLocale($value, [], $locale);    
    });
});
$collection = new Collection(['first', 'second']);
$translated = $collection->toLocale('es');

可用方法

在剩余的大部分集合文档中,我们将讨论 Collection 类上可用的每个方法。记住,所有这些方法都可以链式调用,以流畅地操作底层数组。此外,几乎每个方法都返回一个新的 Collection 实例,允许你在必要时保留集合的原始副本。

方法列表

.collection-method code { font-size: 14px; } .collection-method:not(.first-collection-method) { margin-top: 50px; }

all()

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

$collection = new Collection([1, 2, 3]);
$collection->all(); // [1, 2, 3]

average()

avg 方法的别名。

avg()

avg 方法返回给定键的平均值。

$collection = new Collection([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
]);
$average = $collection->avg('foo');
// 20 
$collection = new Collection([1, 1, 2, 4]);
$average = $collection->avg();
// 2

chunk()

chunk 方法将集合分割成多个给定大小的较小集合。

$collection = new Collection([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->all();
// [[1, 2, 3, 4], [5, 6, 7]]

chunkWhile()

chunkWhile 方法根据给定的回调函数评估将集合分割成多个较小的集合。传递给闭包的 $chunk 变量可以用来检查前面的元素。

$collection = new Collection(str_split('AABBCCCD'));
$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
    return $value === $chunk->last();
});
$chunks->all();
// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]

collapse()

collapse 方法将数组集合折叠成一个单一的扁平集合。

$collection = new Collection([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

collect()

collect 方法返回一个包含当前集合中项的新 Collection 实例。

$collectionA = new Collection([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]

combine()

combine 方法将集合的值作为键,与另一个数组或集合的值结合。

$collection = new Collection(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]

concat()

concat 方法将给定数组或集合的值追加到另一个集合的末尾。

$collection = new Collection(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])
                ->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']

concat 方法会重新索引原始集合上追加的项的键。为了在关联集合中保持键,请参阅 merge 方法。

contains()

《contains》方法用于判断集合中是否包含指定的项。您可以向《contains》方法传递一个闭包,以确定集合中是否存在匹配给定条件测试的元素。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->contains(function (int $value, int $key) {
    return $value > 5;
});
// false

另外,您也可以向《contains》方法传递一个字符串,以确定集合中是否包含指定的项值。

$collection = new Collection(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false

您还可以向《contains》方法传递一个键/值对,这将确定给定的对是否存在于集合中。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false

当检查项值时,《contains》方法使用“宽松”比较,这意味着具有整数值的字符串将与相同值的整数视为相等。使用containsStrict方法来使用“严格”比较进行过滤。

关于《contains》的逆操作,请参阅doesntContain方法。

containsOneItem()

《containsOneItem》方法用于确定集合是否只包含一个项。

$collection = new Collection([])
$collection->containsOneItem();
// false
$collection = new Collection(['1'])
$collection->containsOneItem();
// true
$collection = new Collection(['1', '2'])
$collection->containsOneItem();
// false

containsStrict()

此方法与contains方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

count()

《count》方法返回集合中的总项数。

$collection = new Collection([1, 2, 3, 4]);
$collection->count();
// 4

countBy()

《countBy》方法计算集合中值的出现次数。默认情况下,该方法计算每个元素的出现次数,允许您计算集合中某些“类型”的元素。

$collection = new Collection([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]

您可以向《countBy》方法传递一个闭包来按自定义值计数所有项。

$collection = new Collection(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);
$counted = $collection->countBy(function (string $email) {
    return substr(strrchr($email, "@"), 1);
});
$counted->all();
// ['gmail.com' => 2, 'yahoo.com' => 1]

crossJoin()

《crossJoin》方法将集合的值与给定的数组或集合进行交叉连接,返回一个笛卡尔积,包含所有可能的排列。

$collection = new Collection([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

diff()

《diff》方法根据其值将集合与另一个集合或一个普通的PHP array进行比较。此方法将返回原始集合中不在给定集合中的值。

$collection = new Collection([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]

diffAssoc()

《diffAssoc》方法根据其键和值将集合与另一个集合或一个普通的PHP array进行比较。此方法将返回原始集合中不在给定集合中的键/值对。

$collection = new Collection([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6,
]);
$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6,
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]

diffKeys()

《diffKeys》方法根据其键将集合与另一个集合或一个普通的PHP array进行比较。此方法将返回原始集合中不在给定集合中的键/值对。

$collection = new Collection([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);
$diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);
$diff->all();
// ['one' => 10, 'three' => 30, 'five' => 50]

doesntContain()

《doesntContain》方法用于确定集合是否不包含指定的项。您可以向《doesntContain》方法传递一个闭包,以确定集合中是否存在不匹配给定条件测试的元素。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {    
    return $value < 5;
});
// false

另外,您也可以向《doesntContain》方法传递一个字符串,以确定集合中是否不包含指定的项值。

$collection = new Collection(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Table');
// true
$collection->doesntContain('Desk');
// false

您还可以向《doesntContain》方法传递一个键/值对,这将确定给定的对是否不存在于集合中。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// true

当检查项值时,《doesntContain》方法使用“宽松”比较,这意味着具有整数值的字符串将与相同值的整数视为相等。

duplicates()

《duplicates》方法检索并返回集合中的重复值。

$collection = new Collection(['a', 'b', 'a', 'c', 'b']);
$collection->duplicates();
// [2 => 'a', 4 => 'b']

如果集合包含数组或对象,您可以传递要检查重复值的属性的键。

$employees = new Collection([
    ['email' => 'abigail@example.com', 'position' => 'Developer'],
    ['email' => 'james@example.com', 'position' => 'Designer'],
    ['email' => 'victoria@example.com', 'position' => 'Developer'],
]);
$employees->duplicates('position');
// [2 => 'Developer']

duplicatesStrict()

此方法与duplicates方法的签名相同;然而,所有值都使用“严格”比较进行比较。

each()

each方法遍历集合中的项目,并将每个项目传递给闭包

$collection = new Collection([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
    // ...
});

如果您想停止遍历项目,您可以从闭包中返回false

$collection->each(function (int $item, int $key) {
    if (/* condition */) {
         return false;
    }
});

eachSpread()

eachSpread方法遍历集合的项目,将每个嵌套项的值传递给给定的回调

$collection = new Collection([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function (string $name, int $age) {
    // ...
});

您可以通过从回调中返回false来停止遍历项目

$collection->eachSpread(function (string $name, int $age) {
    return false;
});

every()

every方法可用于验证集合中的所有元素都通过给定的真值测试

$collection = new Collection([1, 2, 3, 4]);
$collection->every(function (int $value, int $key) {
    return $value > 2;
});
// false

如果集合为空,则every方法将返回true

$collection = new Collection([]);
$collection->every(function (int $value, int $key) {
    return $value > 2;
});
// true

except()

except方法返回集合中除指定键外的所有项目

$collection = new Collection(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]

有关except的逆操作,请参阅only方法。

filter()

filter方法使用给定的回调过滤集合,仅保留通过给定真值测试的项目

$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->filter(function (int $value, int $key) { 
   return $value > 2;
});
$filtered->all();
// [3, 4]

如果没有提供回调,则将删除与false等效的所有集合条目

$collection = new Collection([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]

有关filter的逆操作,请参阅reject方法。

first()

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

$collection = new Collection([1, 2, 3, 4]);
$colleciton->first(function (int $value, int $key) {
    return $value > 2;
});
// 3

您还可以不带参数调用first方法以获取集合中的第一个元素。如果集合为空,则返回null

$collection = new Collection([1, 2, 3, 4]);
$collection->first();
// 1

firstOrFail()

firstOrFail方法与first方法相同;然而,如果没有找到结果,将抛出\Exception异常

$collection = new Collection([1, 2, 3, 4]);
$collection->firstOrFail(function (int $value, int $key) {
    return $value > 5;
});
// Throws Exception...

您还可以不带参数调用firstOrFail方法以获取集合中的第一个元素。如果集合为空,将抛出\ItemNotFoundException异常

$collection = new Collection([]);
$collection->firstOrFail();
// Throws Exception...

firstWhere()

firstWhere方法返回具有给定键/值对的第一个集合元素

$collection = new Collection([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]

您还可以使用比较运算符调用firstWhere方法

$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]

where方法一样,您可以向firstWhere方法传递一个参数。在这种情况下,firstWhere方法将返回给定项键的值是“真”的第一个项目

$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]

flatMap()

flatMap方法遍历集合,并将每个值传递给给定的闭包。闭包可以自由修改项并返回它,从而形成一个新的修改后的项目集合。然后,数组通过一个级别进行展开

$collection = new Collection([
    ['name' => 'Sally'],
    ['school' => 'Arkansas'],
    ['age' => 28]
]);
$flattened = $collection->flatMap(function (array $values) {
    return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten()

flatten方法将多维集合压平为一维

$collection = new Collection([
    'name' => 'john',
    'languages' => [
        'php', 'javascript'
    ]
]);
$flattened = $collection->flatten();
$flattened->all();
// ['john', 'php', 'javascript'];

如果需要,您可以向flatten方法传递一个“深度”参数

$collection = new Collection([
    'Apple' => [
        [
            'name' => 'iPhone 6S',
            'brand' => 'Apple'
        ],
    ],
    'Samsung' => [
        [
            'name' => 'Galaxy S7',
            'brand' => 'Samsung'
        ],
    ],
]);
$products = $collection->flatten(1);
$products->values()->all();
/*
    [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
        ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    ]
*/

在此示例中,调用不带深度参数的flatten也会压平嵌套数组,结果为['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。提供深度允许您指定嵌套数组将被压平的层数。

flip()

flip方法交换集合的键与其对应值

$collection = new Collection(['name' => 'john', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['john' => 'name', 'laravel' => 'framework']

forget()

forget方法通过其键从集合中删除项

$collection = new Collection(['name' => 'john', 'framework' => 'laravel']);
$collection->forget('name');
$collection->all();
// ['framework' => 'laravel']

与大多数其他集合方法不同,forget不会返回一个新修改后的集合;它修改被调用的集合。

forPage()

forPage方法返回一个新集合,包含给定页码上应有的项目。该方法接受页码作为其第一个参数,以及每页显示的项目数作为其第二个参数

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]

get()

get方法返回给定键的项。如果键不存在,则返回null

$collection = new Collection(['name' => 'john', 'framework' => 'codeigniter']);
$value = $collection->get('name');
// john

您可以选择性地将默认值作为第二个参数传递

$collection = new Collection(['name' => 'john', 'framework' => 'codeigniter']);
$value = $collection->get('age', 34);
// 34

您甚至可以将回调函数作为方法默认值传递。如果指定的键不存在,则返回回调函数的结果

$collection->get('email', function () {
    return 'john@example.com';
});
// john@example.com

groupBy()

groupBy 方法根据给定的键对集合的项进行分组

$collection = new Collection([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->all();
/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

您不仅可以通过传递字符串 key,还可以通过传递回调函数来实现。回调函数应返回您希望作为分组键的值

$grouped = $collection->groupBy(function (array $item, int $key) {
   return substr($item['account_id'], -3);
});
$grouped->all();
/*
    [
        'x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

可以传递一个数组作为多个分组标准。数组的每个元素将应用于多维数组中的相应级别

$data = new Collection([
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);
$result = $data->groupBy(['skill', function (array $item) {
    return $item['roles'];
    }],
    preserveKeys: true
);
/*
[
    1 => [
        'Role_1' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_2' => [
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_3' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
        ],
    ],
    2 => [
        'Role_1' => [
            30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
        ],
        'Role_2' => [
            40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
        ],
    ],
];
*/

has()

has 方法确定给定的键是否存在于集合中

$collection = new Collection(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['amount', 'price']);
// false

hasAny()

hasAny 方法确定给定的键中的任何一个是否存在于集合中

$collection = new Collection(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->hasAny(['product', 'price']);
// true
$collection->hasAny(['name', 'price']);
// false

implode()

implode 方法将集合中的项连接起来。其参数取决于集合中项的类型。如果集合包含数组或对象,您应该传递要连接的属性的键以及要放在值之间的“粘合”字符串

$collection = new Collection([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair

如果集合包含简单的字符串或数值,您应将“粘合”字符串作为方法的唯一参数传递

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->implode('-');
// '1-2-3-4-5'

如果您想格式化要连接的值,可以向 implode 方法传递闭包

$collection->implode(function (array $item, int $key) {
        return strtoupper($item['product']);
    }, ', ');
// DESK, CHAIR

intersect()

intersect 方法从原始集合中删除不在给定的 array 或集合中存在的任何值。结果集合将保留原始集合的键

$collection = new Collection(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']

intersectByKeys()

intersectByKeys 方法从原始集合中删除不在给定的 array 或集合中存在的任何键及其对应值

$collection = new Collection([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009,
]);
$intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011,
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]

isEmpty()

isEmpty 方法如果集合为空,则返回 true;否则,返回 false

$collection = new Collection([]);
$collection->isEmpty();
// true

isNotEmpty()

isNotEmpty 方法如果集合不为空,则返回 true;否则,返回 false

$collection = new Collection([]);
$collection->isNotEmpty();
// false

join()

join 方法使用字符串连接集合的值。使用此方法的第二个参数,您还可以指定如何将最终元素附加到字符串中

$collection = new Collection(['a', 'b', 'c']);
$collection->join(', '); 
// 'a, b, c'
$collection = new Collection(['a', 'b', 'c']);
$collection->join(', ', ', and '); 
// 'a, b, and c'
$collection = new Collection(['a', 'b']);
$collection->join(', ', ' and '); 
// 'a and b'
$collection = new Collection(['a']);
$collection->join(', ', ' and '); 
// 'a'
$collection = new Collection([]);
$collection->join(', ', ' and '); 
// ''

keyBy()

keyBy 方法根据给定的键对集合进行键化。如果多个项具有相同的键,则新集合中只显示最后一个

$collection = new Collection([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

您还可以向方法传递回调函数。回调函数应返回用于键化集合的值

$keyed = $collection->keyBy(function (array $item, int $key) {
    return strtoupper($item['product_id']);
});
$keyed->all();
/*
    [
        'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

keys()

keys 方法返回集合的所有键

$collection = new Collection([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']

last()

last 方法返回通过给定真值测试的集合中的最后一个元素

$collection = new Collection([1, 2, 3, 4]);
$collection->last(function (int $value, int $key) {
    return $value < 3;
});
// 2

您也可以不带参数调用 last 方法以获取集合中的最后一个元素。如果集合为空,则返回 null

$collection = new Collection([1, 2, 3, 4]);
$collection->last();
// 4

macro()

静态 macro 方法允许您在运行时向 Collection 类添加方法。有关更多信息,请参阅有关扩展集合的文档。

make()

静态 make 方法创建一个新的集合实例。有关更多信息,请参阅创建集合部分。

map()

map 方法遍历集合并将每个值传递给给定的回调函数。回调函数可以自由修改项目并返回它,从而形成一个新集合,其中包含修改后的项目

$collection = new Collection([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function (int $item, int $key) {
    return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]

与大多数其他集合方法一样,map 返回一个新的集合实例;它不会修改被调用的集合。如果您想转换原始集合,请使用 transform 方法。

mapInto()

《mapInto()`方法遍历集合,通过将值传递给构造函数来创建给定类的新的实例

class Currency
{
    /**
     * Create a new currency instance.
     */
    function __construct(
        public string $code
    ) {}
}
$collection = new Collection(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread()

《mapSpread`方法遍历集合的项,将每个嵌套项的值传递给给定的闭包。闭包可以自由地修改项并返回它,从而形成一个新集合,包含修改后的项

$collection = new Collection([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function (int $even, int $odd) {
    return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]

mapToGroups()

《mapToGroups`方法根据给定的闭包对集合的项进行分组。闭包应返回包含单个键/值对的关联数组,从而形成一个新集合,包含分组值

$collection = new Collection([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);
$grouped = $collection->mapToGroups(function (array $item, int $key) {
    return [$item['department'] => $item['name']];
});
$grouped->all();
/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johnny Doe'],
    ]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']

mapWithKeys()

《mapWithKeys`方法遍历集合,并将每个值传递给给定的回调。回调应返回包含单个键/值对的关联数组

$collection = new Collection([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com',
    ]
]);
$keyed = $collection->mapWithKeys(function (array $item, int $key) {
    return [$item['email'] => $item['name']];
});
$keyed->all();
/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/

max()

《max`方法返回给定键的最大值

$max = new Collection([
    ['foo' => 10],
    ['foo' => 20]
]);
$max->max('foo');
// 20
$max = new Collection([1, 2, 3, 4, 5]);
$max->max();
// 5

median()

《median`方法返回给定键的中位数

$median = new Collection([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
])
$median->median('foo');
// 15
$median = new Collection([1, 1, 2, 4]);
$median->median();
// 1.5

merge()

《merge`方法将给定的数组或集合与原始集合合并。如果给定的项中的字符串键与原始集合中的字符串键匹配,则给定的项的值将覆盖原始集合中的值

$collection = new Collection(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]

如果给定的项的键是数字,则值将被追加到集合的末尾

$collection = new Collection(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']

mergeRecursive()

《mergeRecursive`方法递归地将给定的数组或集合与原始集合合并。如果给定的项中的字符串键与原始集合中的字符串键匹配,则这些键的值将合并成一个数组,并且这是递归进行的

$collection = new Collection(['product_id' => 1, 'price' => 100]);
$merged = $collection->mergeRecursive([
    'product_id' => 2,
    'price' => 200,
    'discount' => false
]);
$merged->all();
// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]

min()

《min`方法返回给定键的最小值

$min = new Collection([['foo' => 10], ['foo' => 20]]);
$min->min('foo');
// 10
$min = new Collection([1, 2, 3, 4, 5]);
$min->min();
// 1

mode()

《mode`方法返回给定键的众数

$mode = new Collection([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
]);
$mode->mode('foo');
// [10]
$mode = new Collection([1, 1, 2, 4]);
$mode->mode();
// [1]
$mode = new Collection([1, 1, 2, 2]);
$mode->mode();
// [1, 2]

nth()

《nth`方法创建一个新的集合,包含每n个元素

$collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']

您可以可选地传递一个起始偏移量作为第二个参数

$collection->nth(4, 1);
// ['b', 'f']

only()

《only`方法返回具有指定键的集合中的项

$collection = new Collection([
    'product_id' => 1,
    'name' => 'Desk',
    'price' => 100,
    'discount' => false
]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']

有关《only`的逆操作,请参阅except方法。

pad()

《pad`方法将给定的值填充到数组中,直到数组达到指定的长度。此方法的行为类似于array_pad PHP函数。

要向左填充,您应指定一个负大小。如果给定大小绝对值小于或等于数组的长度,则不会进行填充

$collection = new Collection(['A', 'B', 'C']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['A', 'B', 'C', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'A', 'B', 'C']

partition()

《partition`方法可以与PHP数组解构结合使用,以分离通过给定真值测试的元素和未通过测试的元素

$collection = new Collection([1, 2, 3, 4, 5, 6]);
[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) {
    return $i < 3;
});
 
$underThree->all();
// [1, 2]
 
$equalOrAboveThree->all();
 
// [3, 4, 5, 6]

pipe()

《pipe`方法将集合传递给给定的闭包,并返回执行闭包的结果

$collection = new Collection([1, 2, 3]);
$piped = $collection->pipe(function (Collection $collection) {
    return $collection->sum();
});
// 6

pipeInto()

《pipeInto`方法创建给定类的新的实例,并将集合传递给构造函数

class ResourceCollection
{
    /**
     * Create a new ResourceCollection instance.
     */
    public function __construct(
      public Collection $collection,
    ) {}
}
$collection = new Collection([1, 2, 3]);
$resource = $collection->pipeInto(ResourceCollection::class);
$resource->collection->all();
// [1, 2, 3]

pipeThrough()

《pipeThrough`方法将集合传递给给定的闭包数组,并返回执行闭包的结果

use Imran\Collection\Collection;
$collection = new Collection([1, 2, 3]);
$result = $collection->pipeThrough([
    function (Collection $collection) {
        return $collection->merge([4, 5]);
    },
    function (Collection $collection) {
        return $collection->sum();
    },
]);
// 15

pluck()

《pluck`方法检索给定键的所有值

$collection = new Collection([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']

您还可以指定您希望结果集合如何键控

$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

《pluck`方法还支持使用“点”表示法检索嵌套值

$collection = new Collection([
    [
        'name' => 'Laracon',
        'speakers' => [
            'first_day' => ['Rosa', 'Judith'],
        ],
    ],
    [
        'name' => 'VueConf',
        'speakers' => [
            'first_day' => ['Abigail', 'Joey'],
        ],
    ],
]);
$plucked = $collection->pluck('speakers.first_day');
$plucked->all();
// [['Rosa', 'Judith'], ['Abigail', 'Joey']]

如果存在重复的键,则最后一个匹配的元素将被插入到提取的集合中

$collection = new Collection([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']

pop()

《pop`方法从集合中删除并返回最后一个项

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]

您可以向 pop 方法传递一个整数,以从集合末尾删除并返回多个项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->pop(3);
// new Collection([5, 4, 3])
$collection->all();
// [1, 2]

prepend()

prepend 方法将项目添加到集合的开头。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]

您还可以传递第二个参数来指定附加项目的键。

$collection = new Collection(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]

pull()

pull 方法通过键从集合中删除并返回一个项目。

$collection = new Collection(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']

push()

push 方法将项目追加到集合的末尾。

$collection = new Collection([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]

put()

put 方法在集合中设置指定的键和值。

$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

random 方法从集合中返回一个随机项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (retrieved randomly)

您可以向 random 传递一个整数来指定要随机检索的项目数量。当明确传递要接收的项目数量时,将始终返回一个项目集合。

$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)

如果集合实例中的项目少于请求的数量,则 random 方法将抛出 InvalidArgumentException

random 方法还接受一个闭包,该闭包将接收当前的集合实例。

use Imran\Collection\Collection;
$random = $collection->random(fn (Collection $items) => min(10, count($items)));
$random->all();
// [1, 2, 3, 4, 5] - (retrieved randomly)

range()

range 方法返回一个包含指定范围内整数的集合。

$collection = new Collection();
$collection->range(3, 6);
$collection->all(); // [3, 4, 5, 6]

reduce()

reduce 方法将集合减少到单个值,将每次迭代的每个迭代结果传递给下一次迭代。

$collection = new Collection([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});
// 6

第一次迭代的 $carry 的值是 null;然而,您可以通过向 reduce 传递第二个参数来指定其初始值。

$collection->reduce(function ($carry, $item) {
        return $carry + $item;
    }, 
4);
// 10

reduce 方法还将关联集合中的数组键传递给给定的回调。

$collection = new Collection([
    'usd' => 1400,
    'gbp' => 1200,
    'eur' => 1000,
]);
$ratio = [
    'usd' => 1,
    'gbp' => 1.37,
    'eur' => 1.22,
];
$collection->reduce(function ($carry, $value, $key) use ($ratio) {
    return $carry + ($value * $ratio[$key]);
});
 
// 4264

reduceSpread()

reduceSpread 方法将集合减少到一个值数组,将每次迭代的每个迭代结果传递给下一次迭代。此方法类似于 reduce 方法;然而,它可以接受多个初始值。

$collection = new Collection([[1, 2], [3, 4], [5, 6]]);
$result = $collection->reduceSpread(function ($carry, $item, $key) {
          return [$carry + $item[0] + $item[1]];
}, 0);
// [21]

reject()

reject 方法使用给定的闭包过滤集合。闭包应返回 true 如果项目应从结果集合中删除。

$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->reject(function (int $value, int $key) {
    return $value > 2;
});
$filtered->all();
// [1, 2]

有关 reject 方法的逆操作,请参阅 filter 方法。

replace()

replace 方法的操作类似于 merge;然而,除了覆盖具有字符串键的匹配项目外,replace 方法还将覆盖集合中具有匹配数字键的项目。

$collection = new Collection(['John', 'Abigail', 'James']);
$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);
$replaced->all();
// ['John', 'Victoria', 'James', 'Finn']

replaceRecursive()

此方法类似于 replace,但它将递归到数组中,并将相同的替换过程应用于内部值。

$collection = new Collection([
    'John',
    'Abigail',
    [
        'James',
        'Victoria',
        'Finn'
    ]
]);
$replaced = $collection->replaceRecursive([
    'Charlie',
    2 => [1 => 'King']
]);
 
$replaced->all();
 
// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

reverse()

reverse 方法反转集合项的顺序,保留原始键。

$collection = new Collection(['a', 'b', 'c', 'd', 'e']);
$reversed = $collection->reverse();
$reversed->all();
/*
    [
        4 => 'e',
        3 => 'd',
        2 => 'c',
        1 => 'b',
        0 => 'a',
    ]
*/

search()

search 方法在集合中搜索给定的值,如果找到,则返回其键。如果找不到项目,则返回 false

$collection = new Collection([2, 4, 6, 8]);
$collection->search(4);
// 1

搜索使用“宽松”比较完成,这意味着具有整数值的字符串将视为与相同值的整数相等。要使用“严格”比较,请将 true 作为方法的第二个参数传递。

$collection = new Collection([2, 4, 6, 8]);
$collection->search('4', $strict = true);
// false

或者,您可以为搜索提供自己的闭包,以查找第一个通过给定真值测试的项目。

$collection = new Collection([2, 4, 6, 8]);
$collection->search(function (int $item, int $key) {
    return $item > 5;
});
// 2

shift()

shift 方法从集合中删除并返回第一个项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]

您可以向 shift 方法传递一个整数,以从集合的开始处删除并返回多个项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->shift(3);
// new Collection([1, 2, 3])
$collection->all();
// [4, 5]

shuffle()

shuffle 方法随机打乱集合中的项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)

skip()

《skip》方法返回一个新的集合,从集合的开头移除了指定数量的元素。

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$collection = $collection->skip(4);
$collection->all();
// [5, 6, 7, 8, 9, 10]

skipUntil()

《skipUntil》方法跳过集合中的元素,直到给定的回调函数返回《true》为止,然后返回集合中剩余的元素作为新的集合实例。

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->skipUntil(function (int $item) {
    return $item >= 3;
});
$subset->all();
// [3, 4]

您还可以将一个简单的值传递给《skipUntil》方法,以跳过所有元素,直到找到给定的值。

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->skipUntil(3);
$subset->all();
// [3, 4]

如果找不到给定的值或回调函数永远不会返回《true》,《skipUntil》方法将返回一个空集合。

skipWhile()

《skipWhile》方法在给定的回调函数返回《true》时跳过集合中的元素,然后返回集合中剩余的元素作为新的集合。

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->skipWhile(function (int $item) {
    return $item <= 3;
});
$subset->all();
// [4]

如果回调函数永远不会返回《false》,《skipWhile》方法将返回一个空集合。

slice()

《slice》方法返回从指定索引开始的集合切片。

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]

如果您想限制返回切片的大小,可以将所需的尺寸作为方法的第二个参数传递。

$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]

默认情况下,返回的切片将保留键。如果您不希望保留原始键,可以使用《values》方法来重新索引它们。

sliding()

《sliding》方法返回一个新集合,该集合表示集合中项目的“滑动窗口”视图。

$collection = new Collection([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(2);
$chunks->toArray();
// [[1, 2], [2, 3], [3, 4], [4, 5]]

这在与《eachSpread》方法结合使用时特别有用。

$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {
    $current->total = $previous->total + $current->amount;
});

您还可以可选地传递第二个“步长”值,它确定每个块中第一个项目的距离。

$collection = new Collection([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(3, step: 2);
$chunks->toArray();
// [[1, 2, 3], [3, 4, 5]]

sole()

《sole》方法返回通过给定真值测试的集合中的第一个元素,但只有当真值测试与正好一个元素匹配时。

$collection = new Collection([1, 2, 3, 4]);
$collection->sole(function (int $value, int $key) {
    return $value === 2;
});
// 2

您还可以将键/值对传递给《sole》方法,它将返回与给定的键值对匹配的集合中的第一个元素,但只有当正好有一个元素匹配时。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);
$collection->sole('product', 'Chair');
// ['product' => 'Chair', 'price' => 100]

或者,您也可以不带参数调用《sole》方法,如果集合中只有一个元素,则获取集合的第一个元素。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
]);
$collection->sole();
// ['product' => 'Desk', 'price' => 200]

some()

《some》方法是《contains》方法的别名。

sort()

《sort》方法对集合进行排序。排序后的集合保留原始数组键,因此在下例中,我们将使用《values》方法将键重置为连续编号的索引。

$collection = new Collection([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]

如果您需要更高级的排序,可以将回调函数传递给《sort》方法,并使用您自己的算法。请参阅PHP文档中的uasort,这是集合的《sort》方法内部使用的。

如果您需要排序嵌套数组或对象集合,请参阅《sortBy》和《sortByDesc》方法。

sortBy()

《sortBy》方法根据给定的键对集合进行排序。排序后的集合保留原始数组键,因此在下例中,我们将使用《values》方法将键重置为连续编号的索引。

$collection = new Collection([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

《sortBy》方法接受排序标志作为其第二个参数。

$collection = new Collection([
    ['title' => 'Item 1'],
    ['title' => 'Item 12'],
    ['title' => 'Item 3'],
]);
$sorted = $collection->sortBy('title', SORT_NATURAL);
$sorted->values()->all();
/*
    [
        ['title' => 'Item 1'],
        ['title' => 'Item 3'],
        ['title' => 'Item 12'],
    ]
*/

或者,您也可以传递自己的闭包来确定如何排序集合的值。

$collection = new Collection([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function (array $product, int $key) {
    return count($product['colors']);
});
 
$sorted->values()->all();
 
/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/

如果您想按多个属性对集合进行排序,您可以通过向sortBy方法传递一个排序操作的数组。每个排序操作应是一个数组,包含您想要排序的属性和所需的排序方向。

$collection = new Collection([
    ['name' => 'John Doe', 'age' => 34],
    ['name' => 'Abigail Doe', 'age' => 30],
    ['name' => 'John Doe', 'age' => 36],
    ['name' => 'Abigail Doe', 'age' => 32],
]);
$sorted = $collection->sortBy([
    ['name', 'asc'],
    ['age', 'desc'],
]);
 
$sorted->values()->all();
 
/*
    [
        ['name' => 'Abigail Doe', 'age' => 32],
        ['name' => 'Abigail Doe', 'age' => 30],
        ['name' => 'John Doe', 'age' => 36],
        ['name' => 'John Doe', 'age' => 34],
    ]
*/

当按多个属性对集合进行排序时,您还可以提供定义每个排序操作的闭包。

$collection = new Collection([
    ['name' => 'John', 'age' => 34],
    ['name' => 'Abigail Otwell', 'age' => 30],
    ['name' => 'John', 'age' => 36],
    ['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([fn (array $a, array $b) => $a['name'] <=> $b['name'],fn (array $a, array $b) => $b['age'] <=> $a['age'],]);
$sorted->values()->all();
/*
    [
        ['name' => 'Abigail Doe', 'age' => 32],
        ['name' => 'Abigail Doe', 'age' => 30],
        ['name' => 'John', 'age' => 36],
        ['name' => 'John', 'age' => 34],
    ]
*/

sortByDesc()

此方法与sortBy方法具有相同的签名,但将集合按相反的顺序排序。

sortDesc()

此方法将集合按与sort方法相反的顺序排序。

$collection = new Collection([5, 3, 1, 2, 4]);
$sorted = $collection->sortDesc();
$sorted->values()->all();
// [5, 4, 3, 2, 1]

sort不同,您不能向sortDesc传递闭包。相反,您应该使用sort方法并反转您的比较。

sortKeys()

sortKeys方法按底层关联数组的键对集合进行排序。

$collection = new Collection([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
 
$sorted->all();
 
/*
    [
        'first' => 'John',
        'id' => 22345,
        'last' => 'Doe',
    ]
*/

sortKeysDesc()

此方法与sortKeys方法具有相同的签名,但将集合按相反的顺序排序。

sortKeysUsing()

sortKeysUsing方法使用闭包按底层关联数组的键对集合进行排序。

$collection = new Collection([
    'ID' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);
$sorted = $collection->sortKeysUsing('strnatcasecmp');
 
$sorted->all();
 
/*
    [
        'first' => 'John',
        'ID' => 22345,
        'last' => 'Doe',
    ]
*/

此闭包必须是一个比较函数,它返回一个小于、等于或大于零的整数。有关更多信息,请参阅PHP文档中关于uksort的说明,该函数是sortKeysUsing方法内部使用的PHP函数。

splice()

splice方法从指定的索引开始删除并返回一个项目切片。

$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]

您可以通过传递第二个参数来限制结果集合的大小。

$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]

此外,您还可以传递一个包含新项目的第三个参数,以替换从集合中删除的项目。

$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1, [10, 11]);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 10, 11, 4, 5]

split()

split方法将集合分割成指定数量的组。

$collection = new Collection([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->all();
// [[1, 2], [3, 4], [5]]

splitIn()

splitIn方法将集合分割成指定数量的组,在将剩余部分分配给最后一组之前,先完全填充非终端组。

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$groups = $collection->splitIn(3);
$groups->all();
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

sum()

sum方法返回集合中所有项目的总和。

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->sum();
// 15

如果集合包含嵌套数组或对象,您应该传递一个键,该键将用于确定要累加的值。

$collection = new Collection([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272

此外,您还可以传递自己的闭包来确定要累加的集合值。

    $collection = new Collection([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function (array $product) {
    return count($product['colors']);
});
 
// 6

take()

take方法返回一个包含指定数量项目的新集合。

$collection = new Collection([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]

您还可以传递一个负整数,从集合末尾取出指定数量的项目。

$collection = new Collection([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]

takeUntil()

takeUntil方法返回集合中的项目,直到给定的回调返回true

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->takeUntil(function (int $item) {
    return $item >= 3;
});
 
$subset->all();
 
// [1, 2]

您还可以向takeUntil方法传递一个简单值,以获取直到找到给定值的项目。

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->takeUntil(3);
$subset->all();
// [1, 2]

如果找不到给定值或回调永远不会返回true,则takeUntil方法将返回集合中的所有项目。

takeWhile()

takeWhile方法返回集合中的项目,直到给定的回调返回false

$collection = new Collection([1, 2, 3, 4]);
$subset = $collection->takeWhile(function (int $item) {
    return $item < 3;
});
 
$subset->all();
 
// [1, 2]

如果回调永远不会返回false,则takeWhile方法将返回集合中的所有项目。

tap()

tap方法将集合传递给给定的回调,允许您在特定点“接触”集合并对项目执行一些操作,同时不影响集合本身。然后,tap方法返回集合。

$collection = new Collection([2, 4, 3, 1, 5]);
$collection->sort()
    ->tap(function (Collection $collection) {
        Log::debug('Values after sorting', $collection->values()->all());
    })
    ->shift();
// 1

times()

静态的times方法通过多次调用给定的闭包来创建一个新的集合。

$collection = Collection::times(10, function (int $number) {
    return $number * 9;
});
 
$collection->all();
 
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

toArray()

toArray 方法将集合转换为普通的 PHP array。如果集合的值是 Eloquent 模型,这些模型也会被转换为数组

$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/

toArray 还会将集合中所有是 Arrayable 实例的嵌套对象转换为数组。如果您想获取集合底层的原始数组,请使用 all 方法。

toJson()

toJson 方法将集合转换为 JSON 序列化的字符串

$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'

transform()

transform 方法遍历集合,并对集合中的每个项目调用给定的回调。集合中的项目将被回调返回的值替换

$collection = new Collection([1, 2, 3, 4, 5]);
$collection->transform(function (int $item, int $key) {
    return $item * 2;
});
 
$collection->all();
 
// [2, 4, 6, 8, 10]

与大多数其他集合方法不同,transform 修改了集合本身。如果您想创建一个新的集合,请使用 map 方法。

undot()

undot 方法将使用 "点" 表示法的单维集合展开为多维集合

$person = new Collection([
    'name.first_name' => 'Marie',
    'name.last_name' => 'Valentine',
    'address.line_1' => '2992 Eagle Drive',
    'address.line_2' => '',
    'address.suburb' => 'Detroit',
    'address.state' => 'MI',
    'address.postcode' => '48219'
]);
$person = $person->undot();
 
$person->toArray();
 
/*
    [
        "name" => [
            "first_name" => "Marie",
            "last_name" => "Valentine",
        ],
        "address" => [
            "line_1" => "2992 Eagle Drive",
            "line_2" => "",
            "suburb" => "Detroit",
            "state" => "MI",
            "postcode" => "48219",
        ],
    ]
*/

union()

union 方法将给定的数组添加到集合中。如果给定的数组包含已在原始集合中存在的键,则将优先考虑原始集合的值

$collection = new Collection([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['d']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]

unique()

unique 方法返回集合中所有的唯一项目。返回的集合保留原始数组键,因此在以下示例中,我们将使用 values 方法将键重置为连续编号的索引

$collection = new Collection([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]

在处理嵌套数组或对象时,您可以指定用于确定唯一性的键

$collection = new Collection([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
 
$unique->values()->all();
 
/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/

最后,您还可以将自定义闭包传递给 unique 方法,以指定哪个值应确定项目的唯一性

$unique = $collection->unique(function (array $item) {
    return $item['brand'].$item['type'];
});
 
$unique->values()->all();
 
/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

unique 方法在检查项目值时使用 "宽松" 比较,这意味着具有相同整数值的字符串将被视为等于具有相同值的整数。请使用 uniqueStrict 方法使用 "严格" 比较进行筛选。

uniqueStrict()

此方法与 unique 方法具有相同的签名;然而,所有值都使用 "严格" 比较进行比较。

unless()

unless 方法将在方法给定的第一个参数评估为 true 时执行给定的回调

$collection = new Collection([1, 2, 3]);
$collection->u$collection->unless(true, function (Collection $collection) {
    return $collection->push(4);
});
 
$collection->unless(false, function (Collection $collection) {
    return $collection->push(5);
});
 
$collection->all();
 
// [1, 2, 3, 5]

可以向 unless 方法传递第二个回调。当 unless 方法给定的第一个参数评估为 true 时,将执行第二个回调

$collection = new Collection([1, 2, 3]);
$collection->unless(true, function (Collection $collection) {
    return $collection->push(4);
}, function (Collection $collection) {
    return $collection->push(5);
});
 
$collection->all();
 
// [1, 2, 3, 5]

有关 unless 的逆方法,请参阅 when 方法。

unlessEmpty()

whenNotEmpty 方法的别名。

unlessNotEmpty()

whenEmpty 方法的别名。

unwrap()

静态 unwrap 方法在适用时从给定的值返回集合的底层项目

Collection::unwrap(new Collection('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'

value()

value 方法从集合的第一个元素检索给定的值

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Speaker', 'price' => 400],
]);
$value = $collection->value('price');
// 200

values()

values 方法返回一个新的集合,其键已重置为连续整数

$collection = new Collection([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200],
]);
$values = $collection->values();
$values->all();
/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/

when()

when 方法将在方法给定的第一个参数评估为 true 时执行给定的回调。将提供集合实例和 when 方法给定的第一个参数给闭包

$collection = new Collection([1, 2, 3]);
$collection->when(true, function (Collection $collection, int $value) {
    return $collection->push(4);
});
 
$collection->when(false, function (Collection $collection, int $value) {
    return $collection->push(5);
});
 
$collection->all();
 
// [1, 2, 3, 4]

可以将第二个回调函数传递给 when 方法。当传递给 when 方法的第一个参数评估为 false 时,将执行第二个回调函数。

$collection = new Collection([1, 2, 3]);
$collection->when(false, function (Collection $collection, int $value) {
    return $collection->push(4);
}, function (Collection $collection) {
    return $collection->push(5);
});
 
$collection->all();
 
// [1, 2, 3, 5]

关于 when 方法的逆操作,请参阅 unless 方法。

whenEmpty()

whenEmpty 方法将在集合为空时执行给定的回调函数。

$collection = new Collection(['Michael', 'Tom']);
$collection->whenEmpty(function (Collection $collection) {
    return $collection->push('Adam');
});
 
$collection->all();
 
// ['Michael', 'Tom']
 
 
$collection = new Collection();
 
$collection->whenEmpty(function (Collection $collection) {
    return $collection->push('Adam');
});
 
$collection->all();
 
// ['Adam']

可以将第二个闭包传递给 whenEmpty 方法,当集合不为空时将执行该闭包。

$collection = new Collection(['Michael', 'Tom']);
$collection->whenEmpty(function (Collection $collection) {
    return $collection->push('Adam');
}, function (Collection $collection) {
    return $collection->push('Taylor');
});
 
$collection->all();
 
// ['Michael', 'Tom', 'Taylor']

关于 whenEmpty 方法的逆操作,请参阅 whenNotEmpty 方法。

whenNotEmpty()

whenNotEmpty 方法将在集合不为空时执行给定的回调函数。

$collection = new Collection(['michael', 'tom']);
$collection->whenNotEmpty(function (Collection $collection) {
    return $collection->push('adam');
});
 
$collection->all();
 
// ['michael', 'tom', 'adam']
 
 
$collection = collect();
 
$collection->whenNotEmpty(function (Collection $collection) {
    return $collection->push('adam');
});
 
$collection->all();
 
// []

可以将第二个闭包传递给 whenNotEmpty 方法,当集合为空时将执行该闭包。

$collection = new Collection();
$collection->whenNotEmpty(function (Collection $collection) {
    return $collection->push('adam');
}, function (Collection $collection) {
    return $collection->push('john');
});
 
$collection->all();
 
// ['john']

关于 whenNotEmpty 方法的逆操作,请参阅 whenEmpty 方法。

where()

where 方法通过给定的键/值对过滤集合。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

where 方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将与相同值的整数视为相等。使用 whereStrict 方法进行“严格”比较。

可选地,您可以将比较运算符作为第二个参数传递。支持的运算符有:'===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', 和 '<='。

$collection = new Collection([
    ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
    ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ['name' => 'Sue', 'deleted_at' => null],
]);
$filtered = $collection->where('deleted_at', '!=', null);
$filtered->all();
/*
    [
        ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
        ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ]
*/

whereStrict()

此方法与 where 方法的签名相同;然而,所有值都使用“严格”比较进行比较。

whereBetween()

whereBetween 方法通过确定指定项目值是否在给定范围内来过滤集合。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereIn()

whereIn 方法从集合中删除不具有指定项目值的元素,这些值包含在给定的数组中。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereIn('price', [150, 200]);
$filtered->all();
/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
    ]
*/

whereIn 方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将与相同值的整数视为相等。使用 whereInStrict 方法进行“严格”比较。

whereInStrict()

此方法与 whereIn 方法的签名相同;然而,所有值都使用“严格”比较进行比较。

whereNotBetween()

whereNotBetween 方法通过确定指定项目值是否在给定范围之外来过滤集合。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
 
$filtered->all();
 
/*
    [
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Pencil', 'price' => 30],
    ]
*/

whereNotIn()

whereNotIn 方法从集合中删除具有指定项目值的元素,这些值包含在给定的数组中。

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotIn('price', [150, 200]);
$filtered->all();
/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereNotIn 方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将与相同值的整数视为相等。使用 whereNotInStrict 方法进行“严格”比较。

whereNotInStrict()

此方法与 whereNotIn 方法的签名相同;然而,所有值都使用“严格”比较进行比较。

whereNotNull()

whereNotNull 方法返回集合中给定键不为 null 的项目。

$collection = new Collection([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);
 
$filtered = $collection->whereNotNull('name');
 
$filtered->all();
 
/*
    [
        ['name' => 'Desk'],
        ['name' => 'Bookcase'],
    ]
*/

whereNull()

whereNull 方法返回集合中给定键为 null 的项目。

$collection = new Collection([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);
 
$filtered = $collection->whereNull('name');
 
$filtered->all();
 
/*
    [
        ['name' => null],
    ]
*/

wrap()

静态 wrap 方法在适用时将给定的值包装在集合中。

use Imran\Collection\Collection;
 
$collection = Collection::wrap('John Doe');
 
$collection->all();
 
// ['John Doe']
 
$collection = Collection::wrap(['John Doe']);
 
$collection->all();
 
// ['John Doe']
 
$collection = Collection::wrap(collect('John Doe'));
 
$collection->all();
 
// ['John Doe']

zip()

《zip 方法将给定数组中的值与其在原始集合中的相应索引处的值合并

$collection = new Collection(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]

注意: 此包与 Laravel 集合完全相同,因此这里使用的文档是从 Laravel 网站上获取的,只是为了节省时间。

嗨,我是伊姆兰·阿里!👋

🚀 关于我

资深 全栈 开发者,专注于前端和后端开发。具有动态网络项目开发全过程的丰富经验。具有创新精神、创造力和团队合作能力,拥有前端开发技术学位,拥有7年为各种公司开发、建设和管理网站、应用程序和程序的经验。我寻求获得资深全栈开发者的职位,以便与宝贵的客户分享我的技能、专业知识和经验。

🛠 技能

PHP OOP、Laravel、Codeigniter、JavaScript、Node、React、Vue、Git、HTML、Rest Api、TypeScript、Angular、SCSS、Docker、CI/CD Jenkins、Bootstrap、响应式设计、ASP.NET Core

🔗 关注我

linkedin twitter

许可证

MIT License GPLv3 License AGPL License

贡献

总是欢迎贡献!

查看 contributing.md 了解如何开始。

请遵守本项目的 行为准则