temkaa/simple-collections

这些是简单的数组和对象集合,提供了方便的方法来操作它们。

v0.0.5 2024-08-16 14:03 UTC

README

此项目提供了一组方便操作数据的集合。

安装

composer require temkaa/simple-collections

快速入门

<?php declare(strict_types = 1);

use SimpleCollections\Collection;
use SimpleCollections\Enum\ComparisonOperator;
use SimpleCollections\Enum\SortOrder;
use SimpleCollections\Model\Condition\Compare;
use SimpleCollections\Model\Condition\Exactly;
use SimpleCollections\Model\Sort\ByField;

class SomeClass
{
    public function someArrayFunction(): void
    {
        $products = [
            ['id' => 2, 'name' => 'milk'],
            ['id' => 6, 'name' => 'bread'],
            ['id' => 1, 'name' => 'meat'],
            ['id' => 2, 'name' => 'juice'],
        ];

        var_dump(
            (new Collection($products))->sort(new ByField('name', SortOrder::Desc))->toArray(),
            (new Collection($products))
                ->where(new Compare(field: 'name', operator: ComparisonOperator::GreaterThan, value: 2))
                ->toArray(),
            (new Collection($products))->where(new Exactly(field: 'id', value: 1))->toArray(),
        );
    }

    public function someObjectFunction(): void
    {
        $result = Database::all() // Some database query
        
        var_dump(
            (new Collection($products))->unique()->toArray(),
            (new Collection($products))
                ->map(static fn (object $element): int => $elment->getId())
                ->toArray(),
        );
    }
}

功能

add(mixed $value, int|string|null $key = null): void

向集合中添加新元素。

use SimpleCollections\Collection;

$collection = new Collection([]);
$collection->add(value: 'value');
// or
$collection = new Collection([]);
$collection->add(value: 'value', key: 'key');

chunk(int $size): CollectionInterface[]

按给定大小分块集合中的元素。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$chunks = $collection->chunk(1);

count(): int

返回集合中的元素计数。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$count = $collection->count();

each(callable $callback): CollectionInterface

在集合的每个元素上执行提供的回调。如果回调返回false,则迭代停止。

use SimpleCollections\Collection;

$collection = new Collection([$object1, $object2]);
$collection->each(static function (object $element): bool {
    if ($element->getId() === 1) {
        return false;
    }
    
    $element->setValue(10);
    
    return true;
});

filter(callable $callback): CollectionInterface

使用提供的回调过滤集合。

use SimpleCollections\Collection;

$collection = new Collection([$object1, $object2]);
$newCollection = $collection->filter(static function (object $element): bool => $element->getId() > 10);

first(): mixed

从集合中返回第一个元素,如果集合为空,则返回null。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$first = $collection->first();

has(mixed $value): bool

如果找到元素/键,则返回true,否则返回false。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$exists = $collection->has('element1'); // true
// or
$collection = new Collection(['key' => 'value']);
$exists = $collection->has('key'); // true

isEmpty(): bool

如果集合为空,则返回true,否则返回false。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$isEmpty = $collection->isEmpty(); // false

isNotEmpty(): bool

isEmpty方法相反。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$isNotEmpty = $collection->isNotEmpty(); // true

last(): mixed

返回集合的最后一个元素,如果集合为空,则返回null。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$last = $collection->last();

map(callable $callback): Collection

从提供的回调创建新集合。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$mappedArray = $collection
    ->map(static fn (string $element): string => $element.'1')
    ->toArray(); // ['element11', 'element21']

merge(CollectionInterface $collection, bool $recursive = false): CollectionInterface

将两个集合合并在一起。

use SimpleCollections\Collection;

$collection1 = new Collection(['element1', 'element2']);
$collection2 = new Collection(['element3', 'element4']);
$resultArray = $collection1
    ->merge($collection2)
    ->toArray(); // ['element1', 'element2', 'element3', 'element4']
// or
$collection1 = new Collection(['a' => 'element1', 'b' => 'element2']);
$collection2 = new Collection(['a' => 'element3', 'b' => 'element4']);
$resultArray = $collection1
    ->merge($collection2, recursive: true)
    ->toArray(); // ['a' => ['element1', 'element3'], 'b' => ['element2', 'element4']]

remove(mixed $value): mixed

从集合中删除提供的元素,如果元素不存在,则返回null。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2']);
$removedElement = $collection->remove('element1'); // element1
// or
$collection = new Collection(['a' => 'element1', 'b' => 'element2']);
$removedElement = $collection->remove('a'); // element1

slice(int $offset, ?int $length = null): CollectionInterface

从给定的偏移量按提供的长度切割集合。如果未定义长度,则从给定偏移量获取所有元素。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2', 'element3']);
$slice = $collection->slice(offset: 1)->toArray(); // ['element2', 'element3']
// or
$collection = new Collection(['element1', 'element2', 'element3']);
$slice = $collection->slice(offset: 1, limit: 0)->toArray(); // ['element2']

toArray(): array

返回集合元素。

use SimpleCollections\Collection;

$collection = new Collection(['element1', 'element2', 'element3']);
$array = $collection->toArray(); // ['element1', 'element2', 'element3']

sort(SortCriteriaInterface $criteria): CollectionInterface

按提供的标准排序集合。
按提供的回调排序

use SimpleCollections\Collection;
use SimpleCollections\Model\Sort\ByCallback;

$object1->setId(1);
$object2->setId(2);
$object3->setId(3);

$collection = new Collection([$object3, $object2, $object1]);
$sorted = $collection
    ->sort(new ByCallback(static fn (object $element): int => $element->getId()))
    ->toArray(); // [$object1, $object2, $object3]

按值排序

use SimpleCollections\Collection;
use SimpleCollections\Enum\SortOrder;
use SimpleCollections\Model\Sort\ByValues;

$collection = new Collection([3, 2, 1]);
$sorted = $collection->sort(new ByValues())->toArray(); // [1, 2, 3]
// or
$collection = new Collection([1, 2, 3]);
$sorted = $collection->sort(new ByValues(SortOrder::Desc))->toArray(); // 3, 2, 1]

按键排序

use SimpleCollections\Collection;
use SimpleCollections\Enum\SortOrder;
use SimpleCollections\Model\Sort\ByKeys;

$collection = new Collection(['c' => 8, 'b' => 9, 'a' => 10]);
$sorted = $collection->sort(new ByKeys())->toArray(); // ['a' => 10, 'b' => 9, 'c' => 8]
// or
$collection = new Collection(['c' => 10, 'b' => 9, 'a' => 8]);
$sorted = $collection->sort(new ByKeys(SortOrder::Desc))->toArray(); // ['c' => 10, 'b' => 9, 'a' => 8]

按字段排序

use SimpleCollections\Collection;
use SimpleCollections\Enum\SortOrder;
use SimpleCollections\Model\Sort\ByField;

$collection = new Collection([['field' => 10], ['field' => 5], []]);
$sorted = $collection->sort(new ByField(field: 'field'))->toArray(); // [[], ['field' => 5], ['field' => 10]

$collection = new Collection([['a' => 5], ['a' => 10], []]);
$sorted = $collection
    ->sort(new ByField(field: 'field', order: SortOrder::Desc))
    ->toArray(); [['a' => 10], ['a' => 5], []]

sum(?SumCriteriaInterface $criteria = null): float|int

根据提供的标准返回总和。
默认总和

use SimpleCollections\Collection;

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

按字段总和

use SimpleCollections\Collection;
use SimpleCollections\Model\Sum\ByField;

$collection = new Collection([['a' => 1], ['a' => 2]]);
$sum = $collection->sum(new ByField(field: 'a')); // 3

unique(?UniqueCriteriaInterface $criteria = null): CollectionInterface

根据提供的标准返回唯一元素。
默认唯一

use SimpleCollections\Collection;

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

按字段唯一

use SimpleCollections\Collection;
use SimpleCollections\Model\Unique\ByField;

$collection = new Collection([['a' => 1, 'b' => 2], ['a' => 1, 'b' => 3]]);
$unique = $collection->unique(new ByField(field: 'a'))->toArray(); // [['a' => 1, 'b' => 2]]

where(ConditionInterface $condition): CollectionInterface

返回满足提供的条件的筛选集合。
具有精确命中的Where

use SimpleCollections\Collection;
use SimpleCollections\Model\Condition\Exactly;

$collection = new Collection([1, 2]);
$compared = $collection->where(new Exactly(field: 'a', value: 1))->toArray(); // [1]

具有比较的Where(允许的比较运算符的完整列表可在SimpleCollections\Enum\ComparisonOperator中查看)

use SimpleCollections\Collection;
use SimpleCollections\Enum\ComparisonOperator;
use SimpleCollections\Model\Condition\Compare;

$collection = new Collection([1, 2, 3, 4, 5]);
$compared = $collection
    ->where(new Compare(field: 'a', operator: ComparisonOperator::In, value: [1, 2]))
    ->toArray(); // [1, 2]