hguenot / phpstream
PHPStream 声称是 Java Stream API 的部分 PHP 端口。
V3.0.0
2021-03-07 06:54 UTC
Requires
- php: >=8.0.0
- bentools/iterable-functions: ~1.3
Requires (Dev)
- phpunit/phpunit: >=9
README
PHP Stream 是 PHP 中新的 Java Stream API 的基本端口。
此库可用于过滤、转换或减少任何数组。
持续集成
安装
安装此扩展的首选方式是通过 composer。
运行以下命令:
php composer.phar require --prefer-dist hguenot/phpstream "*"
或者在您的 composer.json
文件的 require 部分添加以下内容:
"hguenot/phpstream": "*"
使用方法
- 以下是该库的基本用法。
// Create a simple array of data $array = [ -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; // Creates a Stream based on the previous array $stream = new \phpstream\Stream($array); // Compute the opposite value of each value $stream = $stream->map(function($value){ return intval($value) * (-1); }); // Get only odd values $stream = $stream->filter(function($value){ return (intval($value) % 2) == 0; }); // Collects data into an array $new_array = $stream->collect(new \phpstream\collectors\ListCollector()); // Computes sum of all elements $sum = $stream->reduce(function($a, $b){ return intval($a) + intval($b); }, 0);
- 所有流操作都可以串联使用
$sum = \phpstream\Stream::of($array) ->map(function($value){ return intval($value) * (-1); }) ->filter(function($value){ return (intval($value) % 2) == 0; }) ->reduce(function($a, $b){ return intval($a) + intval($b); }, 0);
您可以在 PHPUnit 测试中找到更多示例。