nasumilu/iterators
最新稳定版本:v4.3.1
Composer 安装命令:
composer require nasumilu/iterators
包简介
A simple library which adds a fluent and functional interface to PHP Iterator(s).
README 文档
README
Provides a fluent, functional interface to the PHP 8.2 iterable type.
Installation
composer require nasumilu/iterators
Basic Usage
Plain Old PHP Array
Example which uses a plain old php array for the iterable values.
use Nasumilu\Iterators\Iterators;
$iterator = Iterators::from([1, 2, 3, 4])
->map(static fn(int $value): int => $value ** 2)
->filter(static fn(int $value): bool => $value >= 9);
print_r($iterator->values());
Expected Output
Array
(
[2] => 9
[3] => 16
)
By default, the terminating FunctionalIterator::values preserves the offset and gathers the values into an unsorted
array.
PHP Iterators & IteratorAggregate
Example One
Any iterable type maybe used, in this example instead of an array the FunctionalIterator is constructed using
the built-in ArrayIterator.
use \ArrayIterator;
use Nasumilu\Iterators\Iterators;
$values = new ArrayIterator([1, 2, 3, 4]);
$iterator = Iterators::from($values)
->map(static fn(int $value): int => $value ** 2)
->filter(static fn(int $value): bool => $value >= 9);
print_r($iterator->values(preserve_keys: false));
Expected Output
Array
(
[0] => 9
[1] => 16
)
Similar to the previous example the terminating FunctionalIterator::filter returns the values determined by the
predicate callable, except the original offset are no longer preserved.
Example Two
Since any class which implements the ArrayAggregate interface will provide an interable type, they too may also
be used to construct a FunctionalInterator.
use \ArrayObject;
use Nasumilu\Iterators\Iterators;
$values = new ArrayObject([1, 2, 3, 4]);
$iterator = Iterators::from($values)
->map(static fn(int $value): int => $value ** 2)
->filter(static fn(int $value): bool => $value >= 9);
print_r($iterator->values(static fn(int $a, int $b): int => $a <=> $b, false));
print_r($iterator->values(static fn(int $a, int $b): int => $b <=> $a, false));
Expected Output
Array
(
[0] => 9
[1] => 16
)
Array
(
[0] => 16
[1] => 9
)
It is also possible to sort the values by passing a callable which is accepted by the built-in usort function. Seen
in the example the values are first sorted ascending, then descending without preserving the original offsets.
Learn More
统计信息
- 总下载量: 68
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Apache-2.0
- 更新时间: 2023-11-20