yii2mod/collection

基本集合库

安装数: 136,040

依赖者: 4

建议者: 0

安全: 0

星标: 30

关注者: 7

分支: 3

开放问题: 0

类型:yii2-extension

1.3.1 2017-08-27 18:42 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:42:06 UTC


README

为 Yii 2 提供的集合扩展


yii2mod\collection\Collection 类提供了一个流畅、便捷的包装器,用于处理数据数组。

Latest Stable Version Total Downloads License Build Status

支持我们

您的业务依赖于我们的贡献吗?请通过 Patreon 与我们联系并支持我们。所有承诺都将用于分配人力进行维护和新奇功能开发。

安装

安装此扩展的首选方法是通过 composer

运行以下命令

php composer.phar require --prefer-dist yii2mod/collection "*"

或将以下内容添加到您的 composer.json 文件的 require 部分中。

"yii2mod/collection": "*"

创建集合

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

// or via `make` function

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

可用方法

方法列表

all()

all 方法简单地返回集合所表示的底层数组

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

avg 方法返回集合中所有项目的平均值

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

如果集合包含嵌套数组或对象,您应传递一个键,用于确定要计算平均值的值

$collection = new Collection([
    ['id' => 1, 'price' => 150],
    ['id' => 2, 'price' => 250],
]);

$collection->avg('price');

// 200
chunk()

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

$collection = new Collection([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]
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]
combine()

通过使用此集合作为键,另一个集合作为其值来创建集合

$collection = new Collection(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]
contains()

contains 方法确定集合是否包含指定的项目

$collection = new Collection(['city' => 'Alabama', 'country' => 'USA']);

$collection->contains('Alabama');

// true

$collection->contains('New York');

// false

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

$collection = new Collection([
            ['city' => 'Alabama'],
            ['city' => 'New York']
        ]);

$collection->contains('city', 'New York');

// true
count()

count 方法返回集合中的项目总数

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

$collection->count();

// 5
diff()

diff 方法将集合与另一个集合或普通 PHP 数组进行比较

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

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]
each()

each 方法遍历集合中的项目,并将每个项目传递给给定的回调函数

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

every 方法创建一个新集合,该集合包含每第 n 个元素

$collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->every(4);

// ['a', 'e']

您可以选择传递偏移量作为第二个参数

$collection->every(4, 1);

// ['b', 'f']
except()

获取除指定键外的所有项

$collection = new Collection(['id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->except(['price', 'discount']);

$filtered->all();

// ['id' => 1, 'name' => 'Desk']

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

filter()

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

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

$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]
first()

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

Collection::make([1, 2, 3, 4])->first(function ($key, $value) {
    return $value > 2;
});

// 3

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

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

$collection->first();

// 1
last()

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

Collection::make([1, 2, 3, 4])->last(function ($key, $value) {
    return $value > 2;
});

// 4

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

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

$collection->last();

// 5
flatten()

flatten方法将多维集合展平为单维

$collection = new Collection(['language' => 'java', 'languages' => ['php', 'javascript']]);

$collection->flatten();

// ['java', 'php', 'javascript']
flip()

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

$collection = new Collection(['firstName' => 'Igor', 'lastName' => 'Chepurnoy']);

$collection->flip();

// ['Igor' => 'firstName', 'Chepurnoy' => 'lastName']
forget()

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

$collection = new Collection(['firstName' => 'Igor', 'lastName' => 'Chepurnoy']);

$collection->forget('firstName');

$collection->all();

// ['lastName' => 'Chepurnoy']

与大多数其他集合方法不同,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()

通过键从集合中获取项

$collection = new Collection([
'User' => [
    'identity' => [
        'id' => 1
    ]
]
]);

$collection->get('User.identity.id');

// 1

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

$collection->get('User.identity.email', false);

// false
groupBy()

groupBy方法通过给定的键对集合的项目进行分组

$collection = new Collection([
     ['id' => 'id_2', 'name' => 'Bob'],
     ['id' => 'id_2', 'name' => 'John'],
     ['id' => 'id_3', 'name' => 'Frank'],
]);

$grouped = $collection->groupBy('id');

$grouped->toArray();

/*
[
    'id_2' => [
        ['id' => 'id_2', 'name' => 'Bob'],
        ['id' => 'id_2', 'name' => 'John'],
    ],
    'id_3' => [
        ['id' => 'id_3', 'name' => 'Frank'],
    ],
]
*/

除了传递一个字符串键之外,您还可以传递一个回调。该回调应返回您希望按该键分组的价值

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['id'], -2);
});

/*
[
    '_2' => [
        ['id' => 'id_2', 'name' => 'Bob'],
        ['id' => 'id_2', 'name' => 'John'],
    ],
    '_3' => [
        ['id' => 'id_3', 'name' => 'Frank'],
    ],
]
*/
has()

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

$collection = new Collection(['id' => 1, 'name' => 'Igor']);

$collection->has('id');

// true

$collection->has('email');

// false
implode()

将给定键的值连接为一个字符串

$collection = new Collection([
    ['account_id' => 1, 'name' => 'Ben'],
    ['account_id' => 2, 'name' => 'Bob'],
]);

$collection->implode('name', ', ');

// Ben, Bob

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

Collection::make(['Ben', 'Bob'])->implode(' and ')

// Ben and Bob
intersect()

intersect方法删除不在给定数组或集合中存在的任何值

$collection = new Collection(['php', 'python', 'ruby']);

$intersect = $collection->intersect(['python', 'ruby', 'javascript']);

$intersect->all();

// [1 => 'python', 2 => 'ruby']
isEmpty()

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

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

// true
isNotEmpty()

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

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

// false
keyBy()

通过字段或使用回调对关联数组进行键处理

$collection = new Collection([
    ['product_id' => '100', 'name' => 'desk'],
    ['product_id' => '200', 'name' => 'chair'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
  [
     '100' => ['product_id' => '100', 'name' => 'desk'],
     '200' => ['product_id' => '200', 'name' => 'chair'],
  ]
*/

您还可以传递自己的回调,该回调应返回要键集合的值

$collection = new Collection([
    ['product_id' => '100', 'name' => 'desk'],
    ['product_id' => '200', 'name' => 'chair'],
]);

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['name']);
});

$keyed->all();

/*
  [
    'DESK' => ['product_id' => '100', 'name' => 'desk'],
    'CHAIR' => ['product_id' => '200', 'name' => 'chair'],
  ]
*/
keys()

keys方法返回集合的所有键

$collection = new Collection([
    'city' => 'New York',
    'country' => 'USA'
]);

$collection->keys();

// ['city', 'country']
map()

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

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

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

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

max()

获取给定键的最大值

$collection = new Collection([['foo' => 10], ['foo' => 20]]);
$max = $collection->max('foo');

// 20

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

// 5
merge()

将集合与给定项目合并

$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);

$merged = $collection->merge(['price' => 100, 'discount' => false]);

$merged->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]
min()

获取给定键的最小值

$collection = new Collection([['foo' => 10], ['foo' => 20]]);
$min = $collection->min('foo');

// 10

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

// 1
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']
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']
pop()

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

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

$collection->pop();
// 5

$collection->all();

// [1, 2, 3, 4]
prepend()

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

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

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]

您可以选择传递第二个参数来设置插入项的键

$collection = Collection::make(['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()

将项目推送到集合的末尾

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

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]
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。如果该整数大于1,则返回一个项目集合

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (retrieved randomly)
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
reject()

reject 方法使用给定的回调函数过滤集合。回调函数应该对要从中移除的任何项目返回 true。

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

$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [1, 2]
reverse()

reverse 方法反转集合中项的顺序。

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

$reversed = $collection->reverse();

$reversed->all();

// [5, 4, 3, 2, 1]
search()

在集合中搜索给定的值,如果成功则返回相应的键。

$collection = new Collection([2, 4, 6, 8]);

$collection->search(4);

// 1

搜索使用“宽松”比较。要使用严格比较,将 true 作为方法的第二个参数传递。

$collection->search('4', true);

// false
shift()

shift 方法移除并返回集合中的第一个项。

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]
shuffle()

打乱集合中的项。

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

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] // (generated randomly)
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]
sort()

使用回调函数对每个项进行排序。

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

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]
sortBy()

使用给定的回调函数对集合进行排序。

$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],
    ]
*/

您还可以传递自己的回调函数来确定如何排序集合值。

$collection = new Collection([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/
sortByDesc()

此方法与 sortBy() 方法的签名相同,但将按相反的顺序对集合进行排序。

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]
sum()

获取给定值的总和。

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

// 6

如果集合包含嵌套数组或对象,您应该传递一个键来用于确定要汇总哪些值。

$collection = new Collection([
    ['name' => 'Books', 'countOfProduct' => 100],
    ['name' => 'Chairs', 'countOfProduct' => 200],
]);

$collection->sum('countOfProduct');

// 300

此外,您可以传递自己的回调函数来决定要汇总的集合值。

$collection = new Collection([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6
take()

取第一个或最后一个 {$limit} 个项。

$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]
toArray()

将项集合作为普通数组获取。

$collection = new Collection('name');

$collection->toArray();

/*
    ['name']
*/

toArray() 还会将所有嵌套对象转换为数组。如果您想获取原始数组,请使用 all() 方法。

tap()

tap 方法将集合传递给给定的回调函数,允许您在特定点“提取”集合并处理项,同时不影响集合本身。

$collection = new Collection([2, 4, 3, 1, 5]);
$result = $collection->sort()
    ->tap(function ($collection) {
        // Values after sorting
        var_dump($collection->values()->toArray());
    })
    ->shift();
// 1
toJson()

将项集合作为 JSON 获取。

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

$collection->toJson();

// '{"name":"Desk","price":200}'
transform()

使用回调函数转换集合中的每个项。

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

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]

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

unique()

从集合数组中返回唯一项。

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

返回的集合保留原始数组键。在此示例中,我们使用了 values() 方法将键重置为连续编号的索引。

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

$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 = $collection->unique(function ($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'],
    ]
*/
uniqueStrict()

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

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],
    ]
*/
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() 方法在检查项值时使用严格比较。使用 whereLoose() 方法进行过滤。

whereLoose()

此方法与where()方法的签名相同;然而,所有值都使用“宽松”比较来比较。

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' => 'Bookcase', 'price' => 150],
      ['product' => 'Desk', 'price' => 200],
   ]
*/

whereIn()方法在检查项目值时使用严格比较。使用whereInLoose()方法进行“宽松”比较过滤。

whereInLoose()

此方法与whereIn()方法的签名相同;然而,所有值都使用“宽松”比较来比较。

zip()

zip方法将给定数组的值与相应索引处的集合值合并在一起。

$collection = new Collection(['Chair', 'Desk']);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [['Chair', 100], ['Desk', 200]]