rubicon/collection

此包最新版本(1.3.5)没有提供许可信息。

1.3.5 2015-08-08 14:59 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:26:48 UTC


README

搜索

$collection = new Collection(['one', 'two']);

// search by element: true
$collection->contains('one');

// search by key: true
$collection->has(1);

// find the first index of the given element.
$collection->indexOf('one');

// get a Collection instance for all indexes of the given element
$collection->indexesOf('one');

映射 | 减少

reduce() 方法可以返回任何类型的值。

$collection = new Collection([1, 2, 3]);
$result = $collection
	->map(function($item) {
        return $item * 2;
    })
    ->reduce(function($carry, $item) {
        return $item + $carry;
    });
    
echo $result; // 12

过滤 / 拒绝

过滤接受任何有效的回调函数

// creates new collection with only string elements found in $collection
$filtered = $collection->filter('is_string');

// creates new collection with only string keys found in $collection
$filtered = $collection->filter('is_string', Collection::FILTER_KEY);

// Same as above, but reject all string keys
$filtered = $collection->reject('is_string', Collection::FILTER_KEY);

可变接口

各种改变集合状态的运算

$collection = new MutableCollection;

// set / unset key
$collection->set('key', 'value');
$collection->delete('key');

// Push element
$collection->add('value');

// remove all elements 'value'
$collection->remove('value');

// replace every occurrences of the element by a new one
$collection->replace('element', 'new one');

// Clear all collection elements
$collection->clear();