itertools php

其他类别 2025-08-18

Itertools -PHP迭代工具为您的循环供电

受Python的启发 - 设计用于PHP。

特征

Itertools通过提供两种类型的工具来使您成为迭代超级巨星:

  • 循环迭代工具
  • 流迭代工具

循环迭代工具示例

 foreach (Multi:: zip ([ ' a ' , ' b ' ], [ 1 , 2 ]) as [ $ letter , $ number ]) {
    print ( $ letter . $ number );  // a1, b2
}

流迭代工具示例

 $ result = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
    -> distinct ()                 // [1, 2, 3, 4, 5]
    -> map ( fn ( $ x ) => $ x ** 2 )      // [1, 4, 9, 16, 25]
    -> filter ( fn ( $ x ) => $ x < 10 ) // [1, 4, 9]
    -> toSum ();                   // 14

所有功能都可以在iterable收藏中工作:

  • array (类型)
  • Generator (类型)
  • Iterator (接口)
  • Traversable (接口)

读书文档以其他语言翻译:

  • n

快速参考

循环迭代工具

多迭代

迭代器描述代码段
chain连锁多个迭代在一起Multi::chain($list1, $list2)
zip同时迭代多个收集,直到最短的迭代器完成Multi::zip($list1, $list2)
zipEqual迭代多个相等长度的集合,如果长度不相等,则错误Multi::zipEqual($list1, $list2)
zipFilled迭代多个集合,如果长度不相等,则使用填充值Multi::zipFilled($default, $list1, $list2)
zipLongest同时迭代多个收集,直到最长的迭代器完成Multi::zipLongest($list1, $list2)

单个迭代

迭代器描述代码段
chunkwise通过大块迭代Single::chunkwise($data, $chunkSize)
chunkwiseOverlap通过重叠的块迭代Single::chunkwiseOverlap($data, $chunkSize, $overlapSize)
compress过滤元素未选择Single::compress($data, $selectors)
compressAssociative通过未选择的钥匙过滤元素Single::compressAssociative($data, $selectorKeys)
dropWhile当谓词为真时删除元素Single::dropWhile($data, $predicate)
filter过滤到谓词为真的元素Single::filterTrue($data, $predicate)
filterTrue真理元素过滤Single::filterTrue($data)
filterFalse虚假元素的过滤器Single::filterFalse($data)
filterKeys过滤谓词为true的键Single::filterKeys($data, $predicate)
flatMap将功能映射到项目上并结实结果Single::flaMap($data, $mapper)
flatten平坦的多维峰值Single::flatten($data, [$dimensions])
groupBy通过公共元素组数据Single::groupBy($data, $groupKeyFunction, [$itemKeyFunc])
limit迭代到极限Single::limit($data, $limit)
map地图功能到每个项目Single::map($data, $function)
pairwise迭代连续重叠对Single::pairwise($data)
reindex键值估计的勒索键Single::reindex($data, $reindexer)
repeat多次重复一项Single::repeat($item, $repetitions)
reverse迭代元素以相反的顺序Single::reverse($data)
skip跳过元素后迭代Single::skip($data, $count, [$offset])
slice提取一片山质Single::slice($data, [$start], [$count], [$step])
string迭代字符串的字符Single::string($string)
takeWhile迭代元素在谓词为真时Single::takeWhile($data, $predicate)

无限迭代

迭代器描述代码段
count永远依次计数Infinite::count($start, $step)
cycle循环Infinite::cycle($collection)
repeat永远重复一个项目Infinite::repeat($item)

随机迭代

迭代器描述代码段
choice从列表中随机选择Random::choice($list, $repetitions)
coinFlip随机硬币翻转(0或1) Random::coinFlip($repetitions)
number随机数Random::number($min, $max, $repetitions)
percentage 0到1之间的随机百分比Random::percentage($repetitions)
rockPaperScissors随机的岩纸剪刀手Random::rockPaperScissors($repetitions)

数学迭代

迭代器描述代码段
frequencies数据的频率分布Math::frequencies($data, [$strict])
relativeFrequencies数据的相对频率分布Math::relativeFrequencies($data, [$strict])
runningAverage跑步平均积累Math::runningAverage($numbers, $initialValue)
runningDifference运行差异累积Math::runningDifference($numbers, $initialValue)
runningMax运行最大积累Math::runningMax($numbers, $initialValue)
runningMin运行最小积累Math::runningMin($numbers, $initialValue)
runningProduct运行产品积累Math::runningProduct($numbers, $initialValue)
runningTotal运行总积累Math::runningTotal($numbers, $initialValue)

设置和多局迭代

迭代器描述代码段
distinct仅迭代不同的项目Set::distinct($data)
distinctBy仅使用自定义比较器迭代不同的项目Set::distinct($data, $compareBy)
intersection迭代的交点Set::intersection(...$iterables)
intersectionCoercive与强制类型的交叉路口Set::intersectionCoercive(...$iterables)
partialIntersection迭代的部分交集Set::partialIntersection($minCount, ...$iterables)
partialIntersectionCoercive与强制类型的部分交集Set::partialIntersectionCoercive($minCount, ...$iterables)
symmetricDifference迭代的对称差异Set::symmetricDifference(...$iterables)
symmetricDifferenceCoercive与强制类型的对称差异Set::symmetricDifferenceCoercive(...$iterables)
union迭代的结合Set::union(...$iterables)
unionCoercive与型强制结合Set::unionCoercive(...$iterables)

排序迭代

迭代器描述代码段
asort迭代一个维护钥匙的分类集合Sort::asort($data, [$comparator])
sort迭代集合Sort::sort($data, [$comparator])

文件迭代

迭代器描述代码段
readCsv交叉点按线路线CSV文件File::readCsv($fileHandle)
readLines按行迭代文件File::readLines($fileHandle)

转换迭代

迭代器描述代码段
tee迭代重复的迭代器Transform::tee($data, $count)
toArray转换为阵列Transform::toArray($data)
toAssociativeArray转换为关联阵列Transform::toAssociativeArray($data, [$keyFunc], [$valueFunc])
toIterator转换为迭代器Transform::toIterator($data)

概括

概括描述代码段
allMatch如果根据谓词为真,则是正确的Summary::allMatch($data, $predicate)
allUnique如果所有项目都是唯一的,则是真的Summary::allUnique($data, [$strict])
anyMatch如果有任何项目为true,请根据谓词Summary::anyMatch($data, $predicate)
arePermutations如果迭代是彼此的排列,则为thu Summary::arePermutations(...$iterables)
arePermutationsCoercive如果迭代是彼此的置换,则是thue Summary::arePermutationsCoercive(...$iterables)
exactlyN如果完全根据谓词为true,则为thue Summary::exactlyN($data, $n, $predicate)
isEmpty如果它没有物品,则为真实Summary::isEmpty($data)
isPartitioned如果根据谓词在他人面前根据谓词进行划分,则为the Summary::isPartitioned($data, $predicate)
isSorted如果可以分类的话Summary::isSorted($data)
isReversed如果是反向分类的,则为真实Summary::isReversed($data)
noneMatch如果没有根据谓词为true的项目Summary::noneMatch($data, $predicate)
same如果迭代相同,则为thu Summary::same(...$iterables)
sameCount如果迭代的长度相同Summary::sameCount(...$iterables)

减少

减速器描述代码段
toAverage元素的平均平均值Reduce::toAverage($numbers)
toCount减少到可观的长度Reduce::toCount($data)
toFirst降低到其第一个价值Reduce::toFirst($data)
toFirstAndLast减少到其第一个和最后的价值Reduce::toFirstAndLast($data)
toLast降低到最后一个价值Reduce::toLast()
toMax减少到最大元素Reduce::toMax($numbers, [$compareBy])
toMin减少到最小的元素Reduce::toMin($numbers, [$compareBy])
toMinMax减少到上限和下限的数组Reduce::toMinMax($numbers, [$compareBy])
toNth降低到第n个位置Reduce::toNth($data, $position)
toProduct减少其元素的产物Reduce::toProduct($numbers)
toRandomValue从峰值中降低到随机价值Reduce::toRandomValue($data)
toRange减少最大值和最小值的差Reduce::toRange($numbers)
toString简化为连接的字符串Reduce::toString($data, [$separator], [$prefix], [$suffix])
toSum减少其元素的总和Reduce::toSum($numbers)
toValue使用可调用的还原器降低为价值Reduce::toValue($data, $reducer, $initialValue)

流迭代工具

流源

来源描述代码段
of创建一个来自峰值的流Stream::of($iterable)
ofCoinFlips创建随机硬币翻转Stream::ofCoinFlips($repetitions)
ofCsvFile从CSV文件创建流Stream::ofCsvFile($fileHandle)
ofEmpty创建一个空流Stream::ofEmpty()
ofFileLines从文件的行创建流Stream::ofFileLines($fileHandle)
ofRandomChoice创建随机选择的流Stream::ofRandomChoice($items, $repetitions)
ofRandomNumbers创建一个随机数(整数) Stream::ofRandomNumbers($min, $max, $repetitions)
ofRandomPercentage在0到1之间创建一个随机百分比Stream::ofRandomPercentage($repetitions)
ofRange创建一系列数字的流Stream::ofRange($start, $end, $step)
ofRockPaperScissors创建一系列岩纸剪刀手Stream::ofRockPaperScissors($repetitions)

流操作

手术描述代码段
asort分类保持钥匙的峰值源$stream->asort([$comparator])
chainWith带有迭代的链峰值源成单个迭代$stream->chainWith(...$iterables)
compress通过过滤数据未选择来压缩源$stream->compress($selectors)
compressAssociative通过过滤键未选择的键来压缩源$stream->compressAssociative($selectorKeys)
chunkwise通过大块迭代$stream->chunkwise($chunkSize)
chunkwiseOverlap通过重叠的块迭代$stream->chunkwiseOverlap($chunkSize, $overlap)
distinct过滤元素:仅迭代唯一项目$stream->distinct([$strict])
distinctBy过滤元素:仅使用自定义比较器迭代唯一项目$stream->distinct($compareBy)
dropWhile谓词函数为TRUE时,从峰值源中删除元素$stream->dropWhile($predicate)
filter仅适用于谓词函数为true的元素$stream->filterTrue($predicate)
filterTrue仅为真相元素过滤$stream->filterTrue()
filterFalse仅用于虚假元素的过滤$stream->filterFalse()
filterKeys过滤键入谓词功能为真的键$stream->filterKeys($predicate)
flatMap映射功能到元素上,结果平坦$stream->flatMap($function)
flatten平坦的多维流$stream->flatten($dimensions)
frequencies频率分布$stream->frequencies([$strict])
groupBy通过公共数据元素组迭代源$stream->groupBy($groupKeyFunction, [$itemKeyFunc])
infiniteCycle循环逐渐依次逐渐逐渐$stream->infiniteCycle()
intersectionWith相交峰值源和给定的迭代$stream->intersectionWith(...$iterables)
intersection CoerciveWith相交迭代源和给定的迭代与类型的胁迫$stream->intersectionCoerciveWith(...$iterables)
limit限制流的迭代$stream->limit($limit)
map映射功能到元素$stream->map($function)
pairwise来自峰值源的元素返回对$stream->pairwise()
partialIntersectionWith部分相交的峰值和给定的迭代源$stream->partialIntersectionWith( $minIntersectionCount, ...$iterables)
partialIntersection CoerciveWith部分相交的峰值源和给定的迭代与类型的胁迫$stream->partialIntersectionCoerciveWith( $minIntersectionCount, ...$iterables)
reindex键值流的勒索键$stream->reindex($reindexer)
relativeFrequencies相对频率分布$stream->relativeFrequencies([$strict])
reverse流的反向元素$stream->reverse()
runningAverage累积在可触觉源上的平均运行平均值(平均值) $stream->runningAverage($initialValue)
runningDifference累积了超越迭代源的运行差$stream->runningDifference($initialValue)
runningMax累积运行最大源$stream->runningMax($initialValue)
runningMin累积运行最小的最小源$stream->runningMin($initialValue)
runningProduct通过可迭代的来源积累运行的产品$stream->runningProduct($initialValue)
runningTotal累积运行总量超过迭代源$stream->runningTotal($initialValue)
skip跳过流的一些元素$stream->skip($count, [$offset])
slice提取溪流$stream->slice([$start], [$count], [$step])
sort分类流$stream->sort([$comparator])
symmetricDifferenceWith具有峰值源的对称差异和给定的迭代$this->symmetricDifferenceWith(...$iterables)
symmetricDifference CoerciveWith具有峰值源的对称差异和带有类型胁迫的迭代率$this->symmetricDifferenceCoerciveWith( ...$iterables)
takeWhile只要谓词为true $stream->takeWhile($predicate)
unionWith溪流与迭代的结合$stream->unionWith(...$iterables)
unionCoerciveWith与迭代型与类型胁迫的融合结合$stream->unionCoerciveWith(...$iterables)
zipWith同时使用另一个具有峰值的收集来迭代迭代源$stream->zipWith(...$iterables)
zipEqualWith与另一个相等长度同时的迭代源迭代源$stream->zipEqualWith(...$iterables)
zipFilledWith使用默认填充剂的另一个峰值集合的迭代峰值源$stream->zipFilledWith($default, ...$iterables)
zipLongestWith同时使用另一个具有峰值的收集来迭代迭代源$stream->zipLongestWith(...$iterables)

流终端操作

摘要终端操作
终端操作描述代码段
allMatch如果流匹配谓词中的所有项目,则返回true $stream->allMatch($predicate)
allUnique如果流中的所有项目都是唯一的,则返回true $stream->allUnique([$strict]])
anyMatch如果流匹配谓词,则返回true $stream->anyMatch($predicate)
arePermutationsWith如果流的所有迭代排列,则返回true $stream->arePermutationsWith(...$iterables)
arePermutationsCoerciveWith如果所有迭代式排列都带有类型的胁迫,则返回true $stream->arePermutationsCoerciveWith(...$iterables)
exactlyN如果确切的n个项目为true,则返回true $stream->exactlyN($n, $predicate)
isEmpty如果流没有项目,则返回true $stream::isEmpty()
isPartitioned如果根据谓词为true,则返回为true $stream::isPartitioned($predicate)
isSorted如果流按升序排序,则返回true $stream->isSorted()
isReversed如果流按反向降序排序,则返回true $stream->isReversed()
noneMatch如果流匹配谓词中的任何项目都没有返回true $stream->noneMatch($predicate)
sameWith如果流和所有给定的收藏相同,则返回true $stream->sameWith(...$iterables)
sameCountWith如果流和所有给定的收藏的长度相同,则返回true $stream->sameCountWith(...$iterables)
还原终端操作
终端操作描述代码段
toAverage将流的平均值减少到其物品的平均值$stream->toAverage()
toCount将流的长度缩小$stream->toCount()
toFirst将流降低到其第一个值$stream->toFirst()
toFirstAndLast将流降低到其第一个和最后一个值$stream->toFirstAndLast()
toLast将流降至最后一个值$stream->toLast()
toMax将流降低到其最大值$stream->toMax([$compareBy])
toMin将流降至最小值$stream->toMin([$compareBy])
toMinMax将流到上限和下限的阵列减少$stream->toMinMax([$compareBy])
toNth在第n个位置将流降低到价值$stream->toNth($position)
toProduct将流到其物品的产物中减少$stream->toProduct()
toString将流降低到连接的字符串$stream->toString([$separator], [$prefix], [$suffix])
toSum将流减少到其项目的总和$stream->toSum()
toRandomValue将流降低到其中的随机值$stream->toRandomValue()
toRange将流降低到最大值和最小值的差异$stream->toRange()
toValue减少流像array_reduce()函数的流$stream->toValue($reducer, $initialValue)
转换终端操作
终端操作描述代码段
toArray返回流元素的数组$stream->toArray()
toAssociativeArray返回流元素的键值映射$stream->toAssociativeArray($keyFunc, $valueFunc)
tee返回多个相同流的数组$stream->tee($count)
副作用终端操作
终端操作描述代码段
callForEach通过函数对每个项目进行操作$stream->callForEach($function)
print在流中print每个项目$stream->print([$separator], [$prefix], [$suffix])
printLn在新行上print每个项目$stream->printLn()
toCsvFile将流的内容写入CSV文件$stream->toCsvFile($fileHandle, [$headers])
toFile将流的内容写入文件$stream->toFile($fileHandle)

流调试操作

调试操作描述代码段
peek窥视流操作之间的每个元素$stream->peek($peekFunc)
peekStream窥视操作之间的整个流$stream->peekStream($peekFunc)
peekPrint通过在操作之间打印来窥视每个元素$stream->peekPrint()
peekPrintR通过在操作之间进行打印r查看每个元素$stream->peekPrintR()
printR print_r每个项目$stream->printR()
varDump var_dump每个项目$stream->varDump()

设置

将库添加到您的composer.json文件中:

{
  "require" : {
      "markrogoyski/itertools-php" : " 1.* "
  }
}

使用作曲家安装库:

$ php composer.phar install

作曲家将在供应商文件夹中安装Itertools。然后,您可以将以下内容添加到.php文件中以使用自动加载的库。

 require_once __DIR__ . ' /vendor/autoload.php ' ;

另外,请在命令行上使用作曲家来要求并安装Itertools:

 $ php composer.phar require markrogoyski/itertools-php:1.*

最低要求

  • PHP 7.4

用法

所有功能都可以在iterable收藏中工作:

  • array (类型)
  • Generator (类型)
  • Iterator (接口)
  • Traversable (接口)

多迭代

将多个迭代链链分为单个连续序列。

Multi::chain(iterable ...$iterables)

 use IterTools  Multi ;

$ prequels  = [ ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ];
$ originals = [ ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ];

foreach (Multi:: chain ( $ prequels , $ originals ) as $ movie ) {
    print ( $ movie );
}
// 'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi'

拉链

同时迭代多个迭代集合。

Multi::zip(iterable ...$iterables)

 use IterTools  Multi ;

$ languages = [ ' PHP ' , ' Python ' , ' Java ' , ' Go ' ];
$ mascots   = [ ' elephant ' , ' snake ' , ' bean ' , ' gopher ' ];

foreach (Multi:: zip ( $ languages , $ mascots ) as [ $ language , $ mascot ]) {
    print ( " The { $ language } language mascot is an { $ mascot } . " );
}
// The PHP language mascot is an elephant.
// ...

ZIP可以使用多个迭代输入 - 仅限于两个。

 $ names          = [ ' Ryu ' , ' Ken ' , ' Chun Li ' , ' Guile ' ];
$ countries      = [ ' Japan ' , ' USA ' , ' China ' , ' USA ' ];
$ signatureMoves = [ ' hadouken ' , ' shoryuken ' , ' spinning bird kick ' , ' sonic boom ' ];

foreach (Multi:: zip ( $ names , $ countries , $ signatureMoves ) as [ $ name , $ country , $ signatureMove ]) {
    $ streetFighter = new StreetFighter ( $ name , $ country , $ signatureMove );
}

注意:对于不均匀的长度,当最短的峰值耗尽时,迭代会停止。

Zipequal

同时迭代多个具有相等长度的迭代集合。

如果长度不相等,则投掷LengthException ,这意味着至少一个迭代器在另一个迭代器之前结束。

Multi::zipEqual(iterable ...$iterables)

 use IterTools  Multi ;

$ letters = [ ' A ' , ' B ' , ' C ' ];
$ numbers = [ 1 , 2 , 3 ];

foreach (Multi:: zipEqual ( $ letters , $ numbers ) as [ $ letter , $ number ]) {
    // ['A', 1], ['B', 2], ['C', 3]
}

拉链

如果长度不相等,则同时使用默认填充值同时迭代多个迭代集合。

Multi::zipFilled(mixed $filler, iterable ...$iterables)

 use IterTools  Multi ;

$ default = ' ? ' ;
$ letters = [ ' A ' , ' B ' ];
$ numbers = [ 1 , 2 , 3 ];

foreach (Multi:: zipFilled ( $ default , $ letters , $ numbers ) as [ $ letter , $ number ]) {
    // ['A', 1], ['B', 2], ['?', 3]
}

ziplongest

同时迭代多个迭代集合。

Multi::zipLongest(iterable ...$iterables)

对于不均匀的长度,疲惫的迭代将产生null的迭代效果。

 use IterTools  Multi ;

$ letters = [ ' A ' , ' B ' , ' C ' ];
$ numbers = [ 1 , 2 ];

foreach (Multi:: zipLongest ( $ letters , $ numbers ) as [ $ letter , $ number ]) {
    // ['A', 1], ['B', 2], ['C', null]
}

单个迭代

小块

返回一定尺寸的元素。

Single::chunkwise(iterable $data, int $chunkSize)

块大小必须至少1。

 use IterTools  Single ;

$ movies = [
    ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
    ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ,
    ' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];

foreach (Single:: chunkwise ( $ movies , 3 ) as $ trilogy ) {
    $ trilogies [] = $ trilogy ;
}
// [
//     ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith'],
//     ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'],
//     ['The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker]'
// ]

块状重叠

返回重叠的元素。

Single::chunkwiseOverlap(iterable $data, int $chunkSize, int $overlapSize, bool $includeIncompleteTail = true)

  • 块大小必须至少1。
  • 重叠尺寸必须小于块大小。
 use IterTools  Single ;

$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ];

foreach (Single:: chunkwiseOverlap ( $ numbers , 3 , 1 ) as $ chunk ) {
    // [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]
}

压缩

通过过滤未选择的数据来压缩一个峰值。

Single::compress(string $data, $selectors)

 use IterTools  Single ;

$ movies = [
    ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
    ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ,
    ' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ goodMovies = [ 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 ];

foreach (Single:: compress ( $ movies , $ goodMovies ) as $ goodMovie ) {
    print ( $ goodMovie );
}
// 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi', 'The Force Awakens'

压缩关联

通过过滤未选择的键来压缩一个峰值。

Single::compressAssociative(string $data, array $selectorKeys)

  • 仅标准PHP数组/迭代器键(字符串,整数)。
 use IterTools  Single ;

$ starWarsEpisodes = [
    ' I '    => ' The Phantom Menace ' ,
    ' II '   => ' Attack of the Clones ' ,
    ' III '  => ' Revenge of the Sith ' ,
    ' IV '   => ' A New Hope ' ,
    ' V '    => ' The Empire Strikes Back ' ,
    ' VI '   => ' Return of the Jedi ' ,
    ' VII '  => ' The Force Awakens ' ,
    ' VIII ' => ' The Last Jedi ' ,
    ' IX '   => ' The Rise of Skywalker ' ,
];
$ originalTrilogyNumbers = [ ' IV ' , ' V ' , ' VI ' ];

foreach (Single:: compressAssociative ( $ starWarsEpisodes , $ originalTrilogyNumbers ) as $ episode => $ title ) {
    print ( " $ episode : $ title " .  PHP_EOL );
}
// IV: A New Hope
// V: The Empire Strikes Back
// VI: Return of the Jedi

掉线

在谓词函数为真时,从峰值中删除元素。

一旦谓词函数返回false一次,将返回所有剩余元素。

Single::dropWhile(iterable $data, callable $predicate)

 use IterTools  Single ;

$ scores    = [ 50 , 60 , 70 , 85 , 65 , 90 ];
$ predicate = fn ( $ x ) => $ x < 70 ;

foreach (Single:: dropWhile ( $ scores , $ predicate ) as $ score ) {
    print ( $ score );
}
// 70, 85, 65, 90

筛选

过滤掉距离谓词函数为真的仅返回元素的元素。

Single::filter(iterable $data, callable $predicate)

 use IterTools  Single ;

$ starWarsEpisodes   = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ goodMoviePredicate = fn ( $ episode ) => $ episode > 3 && $ episode < 8 ;

foreach (Single:: filter ( $ starWarsEpisodes , $ goodMoviePredicate ) as $ goodMovie ) {
    print ( $ goodMovie );
}
// 4, 5, 6, 7

过滤器true

过滤掉从峰值的元素中删除元素,仅返回的元素。

Single::filterTrue(iterable $data)

 use IterTools  Single ;

$ reportCardGrades = [ 100 , 0 , 95 , 85 , 0 , 94 , 0 ];

foreach (Single:: filterTrue ( $ reportCardGrades ) as $ goodGrade ) {
    print ( $ goodGrade );
}
// 100, 95, 85, 94

过滤器false

过滤掉从峰值返回元素为false的元素中滤除元素。

如果没有提供谓词,则使用数据的布尔值。

Single::filterFalse(iterable $data, callable $predicate)

下载源码

通过命令行克隆项目:

git clone https://github.com/markrogoyski/itertools-php.git