omegaalfa / collection
此库实现了Trie路由逻辑
v0.0.1
2024-06-23 03:01 UTC
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^9.5 || ^10.0
This package is not auto-updated.
Last update: 2024-09-30 02:41:16 UTC
README
本包是一个PHP库,它提供了一个简单而高效的方式来处理数据集合。它提供了一系列用于操作、过滤和转换集合的方法,是任何PHP开发者的强大工具。
安装
composer require omegaalfa/collection
先决条件
PHP 8.1或更高版本
方法
Collection类提供了以下方法
Collection类
- __construct(Iterator|array $items = []): 创建一个新的Collection实例,可选地使用一个数组或一个Iterator初始化。
- addIterator(Iterator|array $collection = []): 向现有集合中添加一个新的Iterator或数组。
- current(): 返回Iterator的当前元素(对于Iterator它是一个集合)。
- setAttribute(mixed $key, mixed $value): 在集合中设置一个属性(如果它是数组)。
- getAttribute(mixed $key): 从集合中获取一个属性(如果它是数组)。
- getIterator(): Traversable: 返回集合的迭代器,允许迭代其项。
- map(callable $callback): Collection: 对集合中的每个项应用回调函数,并返回一个包含转换后项的新Collection。
- filter(callable $callback): Collection: 根据给定的回调函数过滤集合,返回一个只包含满足条件项的新Collection。
- each(callable $callback): Collection: 对集合中的每个项应用回调函数,而不修改原始集合。
- count(): int: 返回集合中项的数量。
- searchValueKey(array $array, string $key): mixed: 根据给定的键在多维数组中搜索值。
- add(mixed $item): void: 向集合中添加一个新的项。
- remove(mixed $item): void: 从集合中移除一个项。
- arrayToGenerator(array $array): Generator: 将数组转换为生成器,允许迭代其元素。
- toArray(): array: 将集合作为数组返回。
LazyFileIterator类
- __construct(string $filePath): 创建一个新的LazyFileIterator实例,指定JSON文件的路径。
- current(): mixed: 返回从文件行中解码的当前JSON对象。
- next(): void: 将迭代器移动到文件中的下一行。
- key(): int: 返回迭代器的当前键(行号)。
- valid(): bool: 检查迭代器是否指向文件中的有效行。
- rewind(): void: 将迭代器重置为文件的开始。
示例
use OmegaAlfa\Collection\Collection; use OmegaAlfa\Collection\LazyFileIterator; // Create a new collection from an array $collection = new Collection([1, 2, 3, 4, 5]); // Iterate over the collection foreach ($collection as $item) { echo $item . PHP_EOL; } // Map the collection $collection->addIterator(new ArrayIterator([6, 7, 8])); $squaredNumbers = $collection->map(function ($item) { return $item * $item; }); // Filter the collection $evenNumbers = $collection->filter(function ($item) { return $item % 2 === 0; }); // Apply a callback to each item in the collection $collection->each(function ($item) { echo "Item: $item" . PHP_EOL; }); // Get the number of items in the collection $count = $collection->count(); // Add an item to the collection $collection->add(6); // Remove an item from the collection $collection->remove(3); // Convert the collection to an array $array = $collection->toArray(); // Search for a value in a multidimensional array $value = $collection->searchValueKey([ 'name' => 'John Doe', 'address' => [ 'street' => 'Main Street', 'city' => 'Anytown', ], ], 'city'); echo $value; // Output: Anytown $iterator = new LazyFileIterator('path/to/your/json_file.json'); $collection = new Collection($iterator); foreach ($collection as $item) { // Process each JSON object from the file echo $item->name . PHP_EOL; }
贡献
请随意提交问题或拉取请求。对于重大更改,请先打开一个问题来讨论您希望更改的内容。
许可
本项目采用MIT许可。有关详细信息,请参阅LICENSE文件。