
受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 (接口)| 迭代器 | 描述 | 代碼段 |
|---|---|---|
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.*
所有功能都可以在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 );
}注意:對於不均勻的長度,當最短的峰值耗盡時,迭代會停止。
同時迭代多個具有相等長度的迭代集合。
如果長度不相等,則投擲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]
}同時迭代多個迭代集合。
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)
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)
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過濾掉從峰值的元素中刪除元素,僅返回的元素。
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的元素中濾除元素。
如果沒有提供謂詞,則使用數據的布爾值。
Single::filterFalse(iterable $data, callable $predicate)
use IterTools Single ;
$ alerts = [ 0 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 ];
foreach (Single:: filterFalse ( $ alerts ) as $ noAlert ) {
print ( $ noAlert );
}
// 0, 0, 0, 0過濾從峰值返回元素中過濾元素,該元素為謂詞函數為true。
Single::filterKeys(iterable $data, callable $predicate)
use IterTools Single ;
$ olympics = [
2000 => ' Sydney ' ,
2002 => ' Salt Lake City ' ,
2004 => ' Athens ' ,
2006 => ' Turin ' ,
2008 => ' Beijing ' ,
2010 => ' Vancouver ' ,
2012 => ' London ' ,
2014 => ' Sochi ' ,
2016 => ' Rio de Janeiro ' ,
2018 => ' Pyeongchang ' ,
2020 => ' Tokyo ' ,
2022 => ' Beijing ' ,
];
$ summerFilter = fn ( $ year ) => $ year % 4 === 0 ;
foreach (Single:: filterKeys ( $ olympics , $ summerFilter ) as $ year => $ hostCity ) {
print ( " $ year : $ hostCity " . PHP_EOL );
}
// 2000: Sydney
// 2004: Athens
// 2008: Beijing
// 2012: London
// 2016: Rio de Janeiro
// 2020: Tokyo僅映射一個函數,僅繪製峰值的元素,然後將結果弄平。
Single::flatMap(iterable $data, callable $mapper)
use IterTools Single ;
$ data = [ 1 , 2 , 3 , 4 , 5 ];
$ mapper = fn ( $ item ) => [ $ item , - $ item ];
foreach (Single:: flatMap ( $ data , $ mapper ) as $ number ) {
print ( $ number . ' ' );
}
// 1 -1 2 -2 3 -3 4 -4 5 -5使多維的效果更平坦。
Single::flatten(iterable $data, int $dimensions = 1)
use IterTools Single ;
$ multidimensional = [ 1 , [ 2 , 3 ], [ 4 , 5 ]];
$ flattened = [];
foreach (Single:: flatten ( $ multidimensional ) as $ number ) {
$ flattened [] = $ number ;
}
// [1, 2, 3, 4, 5]通過公共數據元素組數據。
Single::groupBy(iterable $data, callable $groupKeyFunction, callable $itemKeyFunction = null)
$groupKeyFunction確定了組元素的關鍵。$itemKeyFunction允許每個組成員中的自定義索引。 use IterTools Single ;
$ cartoonCharacters = [
[ ' Garfield ' , ' cat ' ],
[ ' Tom ' , ' cat ' ],
[ ' Felix ' , ' cat ' ],
[ ' Heathcliff ' , ' cat ' ],
[ ' Snoopy ' , ' dog ' ],
[ ' Scooby-Doo ' , ' dog ' ],
[ ' Odie ' , ' dog ' ],
[ ' Donald ' , ' duck ' ],
[ ' Daffy ' , ' duck ' ],
];
$ charactersGroupedByAnimal = [];
foreach (Single:: groupBy ( $ cartoonCharacters , fn ( $ x ) => $ x [ 1 ]) as $ animal => $ characters ) {
$ charactersGroupedByAnimal [ $ animal ] = $ characters ;
}
/*
'cat' => [
['Garfield', 'cat'],
['Tom', 'cat'],
['Felix', 'cat'],
['Heathcliff', 'cat'],
],
'dog' => [
['Snoopy', 'dog'],
['Scooby-Doo', 'dog'],
['Odie', 'dog'],
],
'duck' => [
['Donald', 'duck'],
['Daffy', 'duck'],
*/迭代到極限。
即使達到限制,也會停止更多數據。
Single::limit(iterable $data, int $limit)
use IterTools Single ;
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ limit = 1 ;
foreach (Single:: limit ( $ matrixMovies , $ limit ) as $ goodMovie ) {
print ( $ goodMovie );
}
// 'The Matrix' (and nothing else)將功能映射到每個元素上。
Single::map(iterable $data, callable $function)
use IterTools Single ;
$ grades = [ 100 , 99 , 95 , 98 , 100 ];
$ strictParentsOpinion = fn ( $ g ) => $ g === 100 ? ' A ' : ' F ' ;
foreach (Single:: map ( $ grades , $ strictParentsOpinion ) as $ actualGrade ) {
print ( $ actualGrade );
}
// A, F, F, F, A返回連續的重疊對。
返回空發電機(如果給定收集)包含少於2個元素。
Single::pairwise(iterable $data)
use IterTools Single ;
$ friends = [ ' Ross ' , ' Rachel ' , ' Chandler ' , ' Monica ' , ' Joey ' , ' Phoebe ' ];
foreach (Single:: pairwise ( $ friends ) as [ $ leftFriend , $ rightFriend ]) {
print ( "{ $ leftFriend } and { $ rightFriend }" );
}
// Ross and Rachel, Rachel and Chandler, Chandler and Monica, ...重複一個項目。
Single::repeat(mixed $item, int $repetitions)
use IterTools Single ;
$ data = ' Beetlejuice ' ;
$ repetitions = 3 ;
foreach (Single:: repeat ( $ data , $ repetitions ) as $ repeated ) {
print ( $ repeated );
}
// 'Beetlejuice', 'Beetlejuice', 'Beetlejuice'使用索引器函數的鍵值估計鍵鍵盤鍵。
Single::reindex(string $data, callable $indexer)
use IterTools Single ;
$ data = [
[
' title ' => ' Star Wars: Episode IV – A New Hope ' ,
' episode ' => ' IV ' ,
' year ' => 1977 ,
],
[
' title ' => ' Star Wars: Episode V – The Empire Strikes Back ' ,
' episode ' => ' V ' ,
' year ' => 1980 ,
],
[
' title ' => ' Star Wars: Episode VI – Return of the Jedi ' ,
' episode ' => ' VI ' ,
' year ' => 1983 ,
],
];
$ reindexFunc = fn ( array $ swFilm ) => $ swFilm [ ' episode ' ];
$ reindexedData = [];
foreach (Single:: reindex ( $ data , $ reindexFunc ) as $ key => $ filmData ) {
$ reindexedData [ $ key ] = $ filmData ;
}
// [
// 'IV' => [
// 'title' => 'Star Wars: Episode IV – A New Hope',
// 'episode' => 'IV',
// 'year' => 1977,
// ],
// 'V' => [
// 'title' => 'Star Wars: Episode V – The Empire Strikes Back',
// 'episode' => 'V',
// 'year' => 1980,
// ],
// 'VI' => [
// 'title' => 'Star Wars: Episode VI – Return of the Jedi',
// 'episode' => 'VI',
// 'year' => 1983,
// ],
// ]扭轉一個峰值的元素。
Single::reverse(iterable $data)
use IterTools Single ;
$ words = [ ' Alice ' , ' answers ' , ' your ' , ' questions ' , ' Bob ' ];
foreach (Single:: reverse ( $ words ) as $ word ) {
print ( $ word . ' ' );
}
// Bob questions your answers Alice在可選偏移偏移之後跳過iTable中的n元素。
Single::skip(iterable $data, int $count, int $offset = 0)
use IterTools Single ;
$ movies = [
' The Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' The Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ prequelsRemoved = [];
foreach (Single:: skip ( $ movies , 3 ) as $ nonPrequel ) {
$ prequelsRemoved [] = $ nonPrequel ;
} // Episodes IV - IX
$ onlyTheBest = [];
foreach (Single:: skip ( $ prequelsRemoved , 3 , 3 ) as $ nonSequel ) {
$ onlyTheBest [] = $ nonSequel ;
}
// 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi'提取一片凹處。
Single::slice(iterable $data, int $start = 0, int $count = null, int $step = 1)
use IterTools Single ;
$ olympics = [ 1992 , 1994 , 1996 , 1998 , 2000 , 2002 , 2004 , 2006 , 2008 , 2010 , 2012 , 2014 , 2016 , 2018 , 2020 , 2022 ];
$ winterOlympics = [];
foreach (Single:: slice ( $ olympics , 1 , 8 , 2 ) as $ winterYear ) {
$ winterOlympics [] = $ winterYear ;
}
// [1994, 1998, 2002, 2006, 2010, 2014, 2018, 2022]迭代字符串的個別字符。
Single::string(string $string)
use IterTools Single ;
$ string = ' MickeyMouse ' ;
$ listOfCharacters = [];
foreach (Single:: string ( $ string ) as $ character ) {
$ listOfCharacters [] = $ character ;
}
// ['M', 'i', 'c', 'k', 'e', 'y', 'M', 'o', 'u', 's', 'e']只要謂詞是正確的,就可以從峰值返回元素。
即使以後其他元素最終返回TRUE(與FilterTrue不同),也會立即停止迭代。
Single::takeWhile(iterable $data, callable $predicate)
use IterTools Single ;
$ prices = [ 0 , 0 , 5 , 10 , 0 , 0 , 9 ];
$ isFree = fn ( $ price ) => $ price == 0 ;
foreach (Single:: takeWhile ( $ prices , $ isFree ) as $ freePrice ) {
print ( $ freePrice );
}
// 0, 0 永遠依次計數。
Infinite::count(int $start = 1, int $step = 1)
use IterTools Infinite ;
$ start = 1 ;
$ step = 1 ;
foreach (Infinite:: count ( $ start , $ step ) as $ i ) {
print ( $ i );
}
// 1, 2, 3, 4, 5 ...永遠序列地循環瀏覽集合的元素。
Infinite::cycle(iterable $iterable)
use IterTools Infinite ;
$ hands = [ ' rock ' , ' paper ' , ' scissors ' ];
foreach (Infinite:: cycle ( $ hands ) as $ hand ) {
RockPaperScissors:: playHand ( $ hand );
}
// rock, paper, scissors, rock, paper, scissors, ...永遠重複一項。
Infinite::repeat(mixed $item)
use IterTools Infinite ;
$ dialogue = ' Are we there yet? ' ;
foreach (Infinite:: repeat ( $ dialogue ) as $ repeated ) {
print ( $ repeated );
}
// 'Are we there yet?', 'Are we there yet?', 'Are we there yet?', ... 從一個值數組中生成隨機選擇。
Random::choice(array $items, int $repetitions)
use IterTools Random ;
$ cards = [ ' Ace ' , ' King ' , ' Queen ' , ' Jack ' , ' Joker ' ];
$ repetitions = 10 ;
foreach (Random:: choice ( $ cards , $ repetitions ) as $ card ) {
print ( $ card );
}
// 'King', 'Jack', 'King', 'Ace', ... [random]生成隨機硬幣翻轉(0或1)。
Random::coinFlip(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: coinFlip ( $ repetitions ) as $ coinFlip ) {
print ( $ coinFlip );
}
// 1, 0, 1, 1, 0, ... [random]生成隨機數(整數)。
Random::number(int $min, int $max, int $repetitions)
use IterTools Random ;
$ min = 1 ;
$ max = 4 ;
$ repetitions = 10 ;
foreach (Random:: number ( $ min , $ max , $ repetitions ) as $ number ) {
print ( $ number );
}
// 3, 2, 5, 5, 1, 2, ... [random]在0到1之間產生一個隨機百分比。
Random::percentage(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: percentage ( $ repetitions ) as $ percentage ) {
print ( $ percentage );
}
// 0.30205562629132, 0.59648594775233, ... [random]生成隨機的岩紙剪刀手。
Random::rockPaperScissors(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: rockPaperScissors ( $ repetitions ) as $ rpsHand ) {
print ( $ rpsHand );
}
// 'paper', 'rock', 'rock', 'scissors', ... [random] 返回數據的頻率分佈。
Math::frequencies(iterable $data, bool $strict = true): Generator
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Math ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
foreach (Math:: frequencies ( $ grades ) as $ grade => $ frequency ) {
print ( " $ grade : $ frequency " . PHP_EOL );
}
// A: 2, B: 3, C: 1返回數據的相對頻率分佈。
Math::relativeFrequencies(iterable $data, bool $strict = true): Generator
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Math ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
foreach (Math:: relativeFrequencies ( $ grades ) as $ grade => $ frequency ) {
print ( " $ grade : $ frequency " . PHP_EOL );
}
// A: 0.33, B: 0.5, C: 0.166在數字列表上積累平均運行平均值。
Math::runningAverage(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ grades = [ 100 , 80 , 80 , 90 , 85 ];
foreach (Math:: runningAverage ( $ grades ) as $ runningAverage ) {
print ( $ runningAverage );
}
// 100, 90, 86.667, 87.5, 87在數字列表上累積運行差。
Math::runningDifference(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ credits = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningDifference ( $ credits ) as $ runningDifference ) {
print ( $ runningDifference );
}
// -1, -3, -6, -10, -15提供一個可選的初始值以引導運行差。
use IterTools Math ;
$ dartsScores = [ 50 , 50 , 25 , 50 ];
$ startingScore = 501 ;
foreach (Math:: runningDifference ( $ dartsScores , $ startingScore ) as $ runningScore ) {
print ( $ runningScore );
}
// 501, 451, 401, 376, 326在數字列表上累積運行最大值。
Math::runningMax(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 1 , 2 , 1 , 3 , 5 ];
foreach (Math:: runningMax ( $ numbers ) as $ runningMax ) {
print ( $ runningMax );
}
// 1, 2, 2, 3, 5在數字列表上累積最低運行量。
Math::runningMin(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 3 , 4 , 2 , 5 , 1 ];
foreach (Math:: runningMin ( $ numbers ) as $ runningMin ) {
print ( $ runningMin );
}
// 3, 3, 2, 2, 1在數字列表上累積運行產品。
Math::runningProduct(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningProduct ( $ numbers ) as $ runningProduct ) {
print ( $ runningProduct );
}
// 1, 2, 6, 24, 120提供可選的初始值以引導運行產品。
use IterTools Math ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ initialValue = 5 ;
foreach (Math:: runningProduct ( $ numbers , $ initialValue ) as $ runningProduct ) {
print ( $ runningProduct );
}
// 5, 5, 10, 30, 120, 600在數字列表上累積運行總數。
Math::runningTotal(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ prices = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningTotal ( $ prices ) as $ runningTotal ) {
print ( $ runningTotal );
}
// 1, 3, 6, 10, 15提供一個可選的初始值以導致運行總數。
use IterTools Math ;
$ prices = [ 1 , 2 , 3 , 4 , 5 ];
$ initialValue = 5 ;
foreach (Math:: runningTotal ( $ prices , $ initialValue ) as $ runningTotal ) {
print ( $ runningTotal );
}
// 5, 6, 8, 11, 15, 20 過濾掉從峰值返回不同元素中的元素。
Set::distinct(iterable $data, bool $strict = true)
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Set ;
$ chessSet = [ ' rook ' , ' rook ' , ' knight ' , ' knight ' , ' bishop ' , ' bishop ' , ' king ' , ' queen ' , ' pawn ' , ' pawn ' , ... ];
foreach (Set:: distinct ( $ chessSet ) as $ chessPiece ) {
print ( $ chessPiece );
}
// rook, knight, bishop, king, queen, pawn
$ mixedTypes = [ 1 , ' 1 ' , 2 , ' 2 ' , 3 ];
foreach (Set:: distinct ( $ mixedTypes , false ) as $ datum ) {
print ( $ datum );
}
// 1, 2, 3根據自定義比較函數返回不同元素的元素過濾元素。
Set::distinctBy(iterable $data, callable $compareBy)
use IterTools Set ;
$ streetFighterConsoleReleases = [
[ ' id ' => ' 112233 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' Dreamcast ' ],
[ ' id ' => ' 223344 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 334455 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 445566 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 556677 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 667788 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PC ' ],
];
$ compareBy = fn ( $ sfTitle ) => $ sfTitle [ ' name ' ];
$ uniqueTitles = [];
foreach (Set:: distinctBy ( $ streetFighterConsoleReleases , $ compareBy ) as $ sfTitle ) {
$ uniqueTitles [] = $ sfTitle ;
}
// Contains one SF3 3rd Strike entry and one SFVI entry.迭代迭代的交點。
Set::intersection(iterable ...$iterables)
如果輸入迭代物產生重複的項目,則適用多發路交叉規則。
use IterTools Set ;
$ chessPieces = [ ' rook ' , ' knight ' , ' bishop ' , ' queen ' , ' king ' , ' pawn ' ];
$ shogiPieces = [ ' rook ' , ' knight ' , ' bishop ' 'king', ' pawn ' , ' lance ' , ' gold general ' , ' silver general ' ];
foreach (Set:: intersection ( $ chessPieces , $ shogiPieces ) as $ commonPiece ) {
print ( $ commonPiece );
}
// rook, knight, bishop, king, pawn使用類型的脅迫迭代迭代的交點。
Set::intersectionCoercive(iterable ...$iterables)
如果輸入迭代物產生重複的項目,則適用多發路交叉規則。
use IterTools Set ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 ];
foreach (Set:: intersectionCoercive ( $ numbers , $ numerics ) as $ commonNumber ) {
print ( $ commonNumber );
}
// 1, 2, 3迭代迭代的M-機構交集。
Set::partialIntersection(int $minIntersectionCount, iterable ...$iterables)
use IterTools Set ;
$ staticallyTyped = [ ' c++ ' , ' java ' , ' c# ' , ' go ' , ' haskell ' ];
$ dynamicallyTyped = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
foreach (Set:: partialIntersection ( 2 , $ staticallyTyped , $ dynamicallyTyped , $ supportsInterfaces ) as $ language ) {
print ( $ language );
}
// c++, java, c#, go, php使用類型的脅迫進行迭代的迭代交集。
Set::partialIntersectionCoercive(int $minIntersectionCount, iterable ...$iterables)
use IterTools Set ;
$ set1 = [ 1 , 2 , 3 ],
$ set2 = [ ' 2 ' , ' 3 ' , 4 , 5 ],
$ set3 = [ 1 , ' 2 ' ],
foreach (Set:: partialIntersectionCoercive ( 2 , $ set1 , $ set2 , $ set3 ) as $ partiallyCommonNumber ) {
print ( $ partiallyCommonNumber );
}
// 1, 2, 3迭代迭代的對稱差異。
Set::symmetricDifference(iterable ...$iterables)
如果輸入Iterables產生重複的項目,則適用MultiSet差異規則。
use IterTools Set ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
foreach (Set:: symmetricDifference ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
// 1, 4, 5, 6, 7, 8, 9迭代迭代的對稱差異,並具有類型的脅迫。
Set::symmetricDifferenceCoercive(iterable ...$iterables)
如果輸入Iterables產生重複的項目,則適用MultiSet差異規則。
use IterTools Set ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
foreach (Set:: symmetricDifferenceCoercive ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
// 4, 5, 6, 7, 8, 9迭代迭代的結合。
Set::union(iterable ...$iterables)
如果輸入迭代物產生重複的項目,則適用多材聯合規則。
use IterTools Set ;
$ a = [ 1 , 2 , 3 ];
$ b = [ 3 , 4 ];
$ c = [ 1 , 2 , 3 , 6 , 7 ];
foreach (Set:: union ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
//1, 2, 3, 4, 6, 7迭代迭代與脅迫型的結合。
Set::unionCoercive(iterable ...$iterables)
如果輸入迭代物產生重複的項目,則適用多材聯合規則。
use IterTools Set ;
$ a = [ ' 1 ' , 2 , 3 ];
$ b = [ 3 , 4 ];
$ c = [ 1 , 2 , 3 , 6 , 7 ];
foreach (Set:: unionCoercive ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
//1, 2, 3, 4, 6, 7 在維護關聯密鑰索引關係的同時迭代集合。
Sort::sort(iterable $data, callable $comparator = null)
如果未提供可選的比較器功能,則使用默認排序。
use IterTools Single ;
$ worldPopulations = [
' China ' => 1_439_323_776 ,
' India ' => 1_380_004_385 ,
' Indonesia ' => 273_523_615 ,
' Pakistan ' => 220_892_340 ,
' USA ' => 331_002_651 ,
];
foreach (Sort:: sort ( $ worldPopulations ) as $ country => $ population ) {
print ( " $ country : $ population " . PHP_EOL );
}
// Pakistan: 220,892,340
// Indonesia: 273,523,615
// USA: 331,002,651
// India: 1,380,004,385
// China: 1,439,323,776迭代集合。
Sort::sort(iterable $data, callable $comparator = null)
如果未提供可選的比較器功能,則使用默認排序。
use IterTools Single ;
$ data = [ 3 , 4 , 5 , 9 , 8 , 7 , 1 , 6 , 2 ];
foreach (Sort:: sort ( $ data ) as $ datum ) {
print ( $ datum );
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9 迭代CSV文件的行。
File::readCsv(resource $fileHandle, string $separator = ',', string $enclosure = '"', string $escape = '\')
use IterTools File ;
$ fileHandle = fopen ( ' path/to/file.csv ' , ' r ' );
foreach (File:: readCsv ( $ fileHandle ) as $ row ) {
print_r ( $ row );
}
// Each column field is an element of the array迭代文件的行。
File::readLines(resource $fileHandle)
use IterTools File ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
foreach (File:: readLines ( $ fileHandle ) as $ line ) {
print ( $ line );
}從單個迭代中返回幾個獨立(重複)的迭代器。
Transform::tee(iterable $data, int $count): array
use IterTools Transform ;
$ daysOfWeek = [ ' Mon ' , ' Tues ' , ' Wed ' , ' Thurs ' , ' Fri ' , ' Sat ' , ' Sun ' ];
$ count = 3 ;
[ $ week1 , $ week2 , $ week3 ] = Transform:: tee ( $ data , $ count );
// Each $week contains iterator containing ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']將任何可迭代的陣列轉換為陣列。
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ iterator = new ArrayIterator ([ 1 , 2 , 3 , 4 , 5 ]);
$ array = Transform:: toArray ( $ iterator );將任何迭代的距離轉換為關聯陣列。
Transform::toAssociativeArray(iterable $data, callable $keyFunc = null, callable $valueFunc = null): array
use IterTools Transform ;
$ messages = [ ' message 1 ' , ' message 2 ' , ' message 3 ' ];
$ keyFunc = fn ( $ msg ) => md5 ( $ msg );
$ valueFunc = fn ( $ msg ) => strtoupper ( $ msg );
$ associativeArray = Transform:: toAssociativeArray ( $ messages , $ keyFunc , $ valueFunc );
// [
// '1db65a6a0a818fd39655b95e33ada11d' => 'MESSAGE 1',
// '83b2330607fe8f817ce6d24249dea373' => 'MESSAGE 2',
// '037805d3ad7b10c5b8425427b516b5ce' => 'MESSAGE 3',
// ]將任何迭代器轉換為迭代器。
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ array = [ 1 , 2 , 3 , 4 , 5 ];
$ iterator = Transform:: toIterator ( $ array );如果所有元素匹配謂詞功能,則返回true。
Summary::allMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ finalFantasyNumbers = [ 4 , 5 , 6 ];
$ isOnSuperNintendo = fn ( $ ff ) => $ ff >= 4 && $ ff <= 6 ;
$ boolean = Summary:: allMatch ( $ finalFantasyNumbers , $ isOnSuperNintendo );
// true
$ isOnPlaystation = fn ( $ ff ) => $ ff >= 7 && $ ff <= 9 ;
$ boolean = Summary:: allMatch ( $ finalFantasyNumbers , $ isOnPlaystation );
// false如果所有元素都是唯一的,則返回true。
Summary::allUnique(iterable $data, bool $strict = true): bool
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Summary:: allUnique ( $ items );
// true如果任何元素匹配謂詞函數,則返回true。
Summary::anyMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ answers = [ ' fish ' , ' towel ' , 42 , " don't panic " ];
$ isUltimateAnswer = fn ( $ a ) => a == 42 ;
$ boolean = Summary:: anyMatch ( $ answers , $ isUltimateAnswer );
// true如果所有迭代都是彼此的排列,則返回true。
Summary::arePermutations(iterable ...$iterables): bool
use IterTools Summary ;
$ iter = [ ' i ' , ' t ' , ' e ' , ' r ' ];
$ rite = [ ' r ' , ' i ' , ' t ' , ' e ' ];
$ reit = [ ' r ' , ' e ' , ' i ' , ' t ' ];
$ tier = [ ' t ' , ' i ' , ' e ' , ' r ' ];
$ tire = [ ' t ' , ' i ' , ' r ' , ' e ' ];
$ trie = [ ' t ' , ' r ' , ' i ' , ' e ' ];
$ boolean = Summary:: arePermutations ( $ iter , $ rite , $ reit , $ tier , $ tire , $ trie );
// true如果所有迭代都是用類型的脅迫互相排列的,則返回true。
Summary::arePermutationsCoercive(iterable ...$iterables): bool
use IterTools Summary ;
$ set1 = [ 1 , 2.0 , ' 3 ' ];
$ set2 = [ 2.0 , ' 1 ' , 3 ];
$ set3 = [ 3 , 2 , 1 ];
$ boolean = Summary:: arePermutationsCoercive ( $ set1 , $ set2 , $ set3 );
// true返回為true,如果確切的n項根據謂詞功能為true。
Summary::exactlyN(iterable $data, int $n, callable $predicate): bool
use IterTools Summary ;
$ twoTruthsAndALie = [ true , true , false ];
$ n = 2 ;
$ boolean = Summary:: exactlyN ( $ twoTruthsAndALie , $ n );
// true
$ ages = [ 18 , 21 , 24 , 54 ];
$ n = 4 ;
$ predicate = fn ( $ age ) => $ age >= 21 ;
$ boolean = Summary:: exactlyN ( $ ages , $ n , $ predicate );
// false如果沒有項目為空,則返回true。
Summary::isEmpty(iterable $data): bool
use IterTools Summary ;
$ data = []
$ boolean = Summary:: isEmpty ( $ data );
// true如果給定集合的所有元素滿足謂詞的所有元素都出現在所有不滿意的元素之前,則返回為true。
Summary::isPartitioned(iterable $data, callable $predicate = null): bool
use IterTools Summary ;
$ numbers = [ 0 , 2 , 4 , 1 , 3 , 5 ];
$ evensBeforeOdds = fn ( $ item ) => $ item % 2 === 0 ;
$ boolean = Summary:: isPartitioned ( $ numbers , $ evensBeforeOdds );如果分類元素,則返回為true,否則為false。
Summary::isSorted(iterable $data): bool
use IterTools Summary ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ boolean = Summary:: isSorted ( $ numbers );
// true
$ numbers = [ 3 , 2 , 3 , 4 , 5 ];
$ boolean = Summary:: isSorted ( $ numbers );
// false如果元素是反向排序的,則返回為true,否則為false。
Summary::isReversed(iterable $data): bool
use IterTools Summary ;
$ numbers = [ 5 , 4 , 3 , 2 , 1 ];
$ boolean = Summary:: isReversed ( $ numbers );
// true
$ numbers = [ 1 , 4 , 3 , 2 , 1 ];
$ boolean = Summary:: isReversed ( $ numbers );
// false如果沒有元素匹配謂詞函數,則返回true。
Summary::noneMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ grades = [ 45 , 50 , 61 , 0 ];
$ isPassingGrade = fn ( $ grade ) => $ grade >= 70 ;
$ boolean = Summary:: noneMatch ( $ grades , $ isPassingGrade );
// true如果所有給出的收藏都相同,則返回true。
對於單個迭代或空的迭代列表,返回true。
Summary::same(iterable ...$iterables): bool
use IterTools Summary ;
$ cocaColaIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ pepsiIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ boolean = Summary:: same ( $ cocaColaIngredients , $ pepsiIngredients );
// true
$ cocaColaIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ spriteIngredients = [ ' carbonated water ' , ' sugar ' , ' citric acid ' , ' lemon lime flavorings ' ];
$ boolean = Summary:: same ( $ cocaColaIngredients , $ spriteIngredients );
// false如果所有給定的收藏量具有相同的長度,則返回true。
對於單個迭代或空的迭代列表,返回true。
Summary::sameCount(iterable ...$iterables): bool
use IterTools Summary ;
$ prequels = [ ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ];
$ originals = [ ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ];
$ sequels = [ ' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker ' ];
$ boolean = Summary:: sameCount ( $ prequels , $ originals , $ sequels );
// true
$ batmanMovies = [ ' Batman Begins ' , ' The Dark Knight ' , ' The Dark Knight Rises ' ];
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ result = Summary:: sameCount ( $ batmanMovies , $ matrixMovies );
// false 減少到平均值。
如果收集為空,則返回null。
Reduce::toAverage(iterable $data): float
use IterTools Reduce ;
$ grades = [ 100 , 90 , 95 , 85 , 94 ];
$ finalGrade = Reduce:: toAverage ( $ numbers );
// 92.8減少了它的長度。
Reduce::toCount(iterable $data): int
use IterTools Reduce ;
$ someIterable = ImportantThing:: getCollectionAsIterable ();
$ length = Reduce:: toCount ( $ someIterable );
// 3將其減少到其第一個元素。
Reduce::toFirst(iterable $data): mixed
拋出LengthException如果收集為空。
use IterTools Reduce ;
$ medals = [ ' gold ' , ' silver ' , ' bronze ' ];
$ first = Reduce:: toFirst ( $ medals );
// gold將其減少到其第一個也是最後一個元素。
Reduce::toFirstAndLast(iterable $data): array{mixed, mixed}
拋出LengthException如果收集為空。
use IterTools Reduce ;
$ weekdays = [ ' Monday ' , ' Tuesday ' , ' Wednesday ' , ' Thursday ' , ' Friday ' ];
$ firstAndLast = Reduce:: toFirstAndLast ( $ weekdays );
// [Monday, Friday]將其減少到其最後一個元素。
Reduce::toLast(iterable $data): mixed
拋出LengthException如果收集為空。
use IterTools Reduce ;
$ gnomesThreePhasePlan = [ ' Collect underpants ' , ' ? ' , ' Profit ' ];
$ lastPhase = Reduce:: toLast ( $ gnomesThreePhasePlan );
// Profit減少到最大值。
Reduce::toMax(iterable $data, callable $compareBy = null): mixed|null
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。 use IterTools Reduce ;
$ numbers = [ 5 , 3 , 1 , 2 , 4 ];
$ result = Reduce:: toMax ( $ numbers );
// 5
$ movieRatings = [
[
' title ' => ' Star Wars: Episode IV - A New Hope ' ,
' rating ' => 4.6
],
[
' title ' => ' Star Wars: Episode V - The Empire Strikes Back ' ,
' rating ' => 4.8
],
[
' title ' => ' Star Wars: Episode VI - Return of the Jedi ' ,
' rating ' => 4.6
],
];
$ compareBy = fn ( $ movie ) => $ movie [ ' rating ' ];
$ highestRatedMovie = Reduce:: toMax ( $ movieRatings , $ compareBy );
// [
// 'title' => 'Star Wars: Episode V - The Empire Strikes Back',
// 'rating' => 4.8
// ];減少到最小值。
Reduce::toMin(iterable $data, callable $compareBy = null): mixed|null
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。 use IterTools Reduce ;
$ numbers = [ 5 , 3 , 1 , 2 , 4 ];
$ result = Reduce:: toMin ( $ numbers );
// 1
$ movieRatings = [
[
' title ' => ' The Matrix ' ,
' rating ' => 4.7
],
[
' title ' => ' The Matrix Reloaded ' ,
' rating ' => 4.3
],
[
' title ' => ' The Matrix Revolutions ' ,
' rating ' => 3.9
],
[
' title ' => ' The Matrix Resurrections ' ,
' rating ' => 2.5
],
];
$ compareBy = fn ( $ movie ) => $ movie [ ' rating ' ];
$ lowestRatedMovie = Reduce:: toMin ( $ movieRatings , $ compareBy );
// [
// 'title' => 'The Matrix Resurrections',
// 'rating' => 2.5
// ]還原到其上限和下邊界的陣列(最大和最小)。
Reduce::toMinMax(iterable $numbers, callable $compareBy = null): array
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。[null, null]如果給定收集為空。 use IterTools Reduce ;
$ numbers = [ 1 , 2 , 7 , - 1 , - 2 , - 3 ];
[ $ min , $ max ] = Reduce:: toMinMax ( $ numbers );
// [-3, 7]
$ reportCard = [
[
' subject ' => ' history ' ,
' grade ' => 90
],
[
' subject ' => ' math ' ,
' grade ' => 98
],
[
' subject ' => ' science ' ,
' grade ' => 92
],
[
' subject ' => ' english ' ,
' grade ' => 85
],
[
' subject ' => ' programming ' ,
' grade ' => 100
],
];
$ compareBy = fn ( $ class ) => $ class [ ' grade ' ];
$ bestAndWorstSubject = Reduce:: toMinMax ( $ reportCard , $ compareBy );
// [
// [
// 'subject' => 'english',
// 'grade' => 85
// ],
// [
// 'subject' => 'programming',
// 'grade' => 100
// ],
// ]在第n個位置降低到價值。
Reduce::toNth(iterable $data, int $position): mixed
use IterTools Reduce ;
$ lotrMovies = [ ' The Fellowship of the Ring ' , ' The Two Towers ' , ' The Return of the King ' ];
$ rotk = Reduce:: toNth ( $ lotrMovies , 2 );
// 20減少了其元素的產物。
如果收集為空,則返回null。
Reduce::toProduct(iterable $data): number|null
use IterTools Reduce ;
$ primeFactors = [ 5 , 2 , 2 ];
$ number = Reduce:: toProduct ( $ primeFactors );
// 20減少給定的收集到其中的隨機值。
Reduce::toRandomValue(iterable $data): mixed
use IterTools Reduce ;
$ sfWakeupOptions = [ ' mid ' , ' low ' , ' overhead ' , ' throw ' , ' meaty ' ];
$ wakeupOption = Reduce:: toRandomValue ( $ sfWakeupOptions );
// e.g., throw減少了收集到其範圍(最大和最小之間的差異)。
Reduce::toRange(iterable $numbers): int|float
返回0如果源為空的源。
use IterTools Reduce ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Reduce:: toRange ( $ numbers );
// 20還原為連接所有元素的字符串。
Reduce::toString(iterable $data, string $separator = '', string $prefix = '', string $suffix = ''): string
use IterTools Reduce ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
$ string = Reduce:: toString ( $ words );
// IterToolsPHPv1.0
$ string = Reduce:: toString ( $ words , ' - ' );
// IterTools-PHP-v1.0
$ string = Reduce:: toString ( $ words , ' - ' , ' Library: ' );
// Library: IterTools-PHP-v1.0
$ string = Reduce:: toString ( $ words , ' - ' , ' Library: ' , ' ! ' );
// Library: IterTools-PHP-v1.0!減少其元素的總和。
Reduce::toSum(iterable $data): number
use IterTools Reduce ;
$ parts = [ 10 , 20 , 30 ];
$ sum = Reduce:: toSum ( $ parts );
// 60使用還原函數將元素減少到單個值。
Reduce::toValue(iterable $data, callable $reducer, mixed $initialValue): mixed
use IterTools Reduce ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ sum = fn ( $ carry , $ item ) => $ carry + $ item ;
$ result = Reduce:: toValue ( $ input , $ sum , 0 );
// 15 流提供了一個流利的接口,可以通過操作管道轉換數組和迭代。
流由:
$ 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 (); // 14foreach循環迭代的。 $ 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]
foreach ( $ result as $ item ) {
// 1, 4, 9
}從一個值得一提的地方創建流。
Stream::of(iterable $iterable): Stream
use IterTools Stream ;
$ iterable = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ iterable )
-> chainWith ([ 4 , 5 , 6 ], [ 7 , 8 , 9 ])
-> zipEqualWith ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ])
-> toValue ( fn ( $ carry , $ item ) => $ carry + array_sum ( $ item ));
// 90 創建n個隨機硬幣翻轉的流。
Stream::ofCoinFlips(int $repetitions): Stream
use IterTools Stream ;
$ result = Stream:: ofCoinFlips ( 10 )
-> filterTrue ()
-> toCount ();
// 5 (random) 創建CSV文件的行流。
Stream::ofCsvFile(resource $fileHandle, string $separator = ',', string $enclosure = '"', string = $escape = '\'): Stream
use IterTools Stream ;
$ fileHandle = fopen ( ' path/to/file.csv ' , ' r ' );
$ result = Stream:: of ( $ fileHandle )
-> toArray ();創建一無所有的流。
Stream::ofEmpty(): Stream
use IterTools Stream ;
$ result = Stream:: ofEmpty ()
-> chainWith ([ 1 , 2 , 3 ])
-> toArray ();
// 1, 2, 3 創建文件流。
Stream::ofFileLines(resource $fileHandle): Stream
use IterTools Stream ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
$ result = Stream:: of ( $ fileHandle )
-> map ( ' strtoupper ' );
-> toArray ();從一個值數組中創建隨機選擇的流。
Stream::ofRandomChoice(array $items, int $repetitions): Stream
use IterTools Stream ;
$ languages = [ ' PHP ' , ' Go ' , ' Python ' ];
$ languages = Stream:: ofRandomChoice ( $ languages , 5 )
-> toArray ();
// 'Go', 'PHP', 'Python', 'PHP', 'PHP' (random) 創建隨機數(整數)的流。
Stream::ofRandomNumbers(int $min, int $max, int $repetitions): Stream
use IterTools Stream ;
$ min = 1 ;
$ max = 3 ;
$ reps = 7 ;
$ result = Stream:: ofRandomNumbers ( $ min , $ max , $ reps )
-> toArray ();
// 1, 2, 2, 1, 3, 2, 1 (random) 創建在0到1之間的隨機百分比流。
Stream::ofRandomPercentage(int $repetitions): Stream
use IterTools Stream ;
$ stream = Stream:: ofRandomPercentage ( 3 )
-> toArray ();
// 0.8012566976245, 0.81237281724151, 0.61676896329459 [random] 創建一系列數字的流。
Stream::ofRange(int|float $start, int|float $end, int|float $step = 1): Stream
use IterTools Stream ;
$ numbers = Stream:: ofRange ( 0 , 5 )
-> toArray ();
// 0, 1, 2, 3, 4, 5 創建岩紙剪刀手的流。
Stream::ofRockPaperScissors(int $repetitions): Stream
use IterTools Stream ;
$ rps = Stream:: ofRockPaperScissors ( 5 )
-> toArray ();
// 'paper', 'rock', 'rock', 'scissors', 'paper' [random]分類流,維護鍵。
$stream->asort(callable $comparator = null)
如果沒有提供比較器,則必須可比較峰值源的元素。
use IterTools Stream ;
$ worldPopulations = [
' China ' => 1_439_323_776 ,
' India ' => 1_380_004_385 ,
' Indonesia ' => 273_523_615 ,
' USA ' => 331_002_651 ,
];
$ result = Stream:: of ( $ worldPopulations )
-> filter ( fn ( $ pop ) => $ pop > 300_000_000 )
-> asort ()
-> toAssociativeArray ();
// USA => 331_002_651,
// India => 1_380_004_385,
// China => 1_439_323_776, 將流鏈接的其他資源一起返回到一個連續的流中。
$stream->chainWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> chainWith ([ 4 , 5 , 6 ])
-> chainWith ([ 7 , 8 , 9 ])
-> toArray ();
// 1, 2, 3, 4, 5, 6, 7, 8, 9 通過濾除未選擇的數據來壓縮新流。
$stream->compress(iterable $selectors): Stream
選擇器指示哪些數據。真值選擇項目。錯誤的值過濾數據。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> compress ([ 0 , 1 , 1 ])
-> toArray ();
// 2, 3 通過過濾未選擇的鍵來壓縮新流。
$stream->compressAssociative(array $keys): Stream
use IterTools Stream ;
$ 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 ' ,
];
$ sequelTrilogyNumbers = [ ' VII ' , ' VIII ' , ' IX ' ];
$ sequelTrilogy = Stream:: of ( $ starWarsEpisodes )
-> compressAssociative ( $ sequelTrilogyNumbers )
-> toAssociativeArray ();
// 'VII' => 'The Force Awakens',
// 'VIII' => 'The Last Jedi',
// 'IX' => 'The Rise of Skywalker', 返回由流中元素組成的流。
$stream->chunkwise(int $chunkSize): Stream
塊大小必須至少1。
use IterTools Stream ;
$ friends = [ ' Ross ' , ' Rachel ' , ' Chandler ' , ' Monica ' , ' Joey ' ];
$ result = Stream:: of ( $ friends )
-> chunkwise ( 2 )
-> toArray ();
// ['Ross', 'Rachel'], ['Chandler', 'Monica'], ['Joey'] 返回由流中元素重疊的元素組成的流。
$stream->chunkwiseOverlap(int $chunkSize, int $overlapSize, bool $includeIncompleteTail = true): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ result = Stream:: of ( $ friends )
-> chunkwiseOverlap ( 3 , 1 )
-> toArray ()
// [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9] 返回流從流中過濾的元素,僅返回不同的元素。
$stream->distinct(bool $strict = true): Stream
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Stream ;
$ input = [ 1 , 2 , 1 , 2 , 3 , 3 , ' 1 ' , ' 1 ' , ' 2 ' , ' 3 ' ];
$ stream = Stream:: of ( $ input )
-> distinct ()
-> toArray ();
// 1, 2, 3, '1', '2', '3'
$ stream = Stream:: of ( $ input )
-> distinct ( false )
-> toArray ();
// 1, 2, 3 返回流從流中過濾元素,僅根據自定義比較函數返回不同的元素。
$stream->distinctBy(callable $compareBy): Stream
use IterTools Stream ;
$ streetFighterConsoleReleases = [
[ ' id ' => ' 112233 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' Dreamcast ' ],
[ ' id ' => ' 223344 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 334455 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 445566 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 556677 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 667799 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PC ' ],
];
$ stream = Stream:: of ( $ streetFighterConsoleReleases )
-> distinctBy ( fn ( $ sfTitle ) => $ sfTitle [ ' name ' ])
-> toArray ();
// Contains one SF3 3rd Strike entry and one SFVI entry 在謂詞函數為真時,從流中刪除元素。
$stream->dropWhile(callable $predicate): Stream
一旦謂詞函數返回false一次,將返回所有剩餘元素。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ]
$ result = Stream:: of ( $ input )
-> dropWhile ( fn ( $ value ) => $ value < 3 )
-> toArray ();
// 3, 4, 5 從流中過濾元素僅在謂詞函數為真的地方保存元素。
$stream->filter(callable $predicate): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> filter ( fn ( $ value ) => $ value > 0 )
-> toArray ();
// 1, 2, 3 從流中過濾元素,僅保留真實的元素。
$stream->filterTrue(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterTrue ()
-> toArray ();
// 1, 2, 3, 4 從流中過濾元素,僅保留虛假的元素。
$stream->filterFalse(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterFalse ()
-> toArray ();
// 0, 0 從流中過濾元素,僅保留鍵上謂詞功能的元素是正確的。
$stream->filterKeys(callable $filter): Stream
$ olympics = [
2000 => ' Sydney ' ,
2002 => ' Salt Lake City ' ,
2004 => ' Athens ' ,
2006 => ' Turin ' ,
2008 => ' Beijing ' ,
2010 => ' Vancouver ' ,
2012 => ' London ' ,
2014 => ' Sochi ' ,
2016 => ' Rio de Janeiro ' ,
2018 => ' Pyeongchang ' ,
2020 => ' Tokyo ' ,
2022 => ' Beijing ' ,
];
$ winterFilter = fn ( $ year ) => $ year % 4 === 2 ;
$ result = Stream:: of ( $ olympics )
-> filterKeys ( $ winterFilter )
-> toAssociativeArray ();
}
// 2002 => Salt Lake City
// 2006 => Turin
// 2010 => Vancouver
// 2014 => Sochi
// 2018 => Pyeongchang
// 2022 => Beijing 將函數映射到流的元素上,並使結果變平。
$stream->flatMap(callable $mapper): Stream
$ data = [ 1 , 2 , 3 , 4 , 5 ];
$ mapper fn ( $ item ) => ( $ item % 2 === 0 ) ? [ $ item , $ item ] : $ item ;
$ result = Stream:: of ( $ data )
-> flatMap ( $ mapper )
-> toArray ();
// [1, 2, 2, 3, 4, 4, 5] 弄平了多維流。
$stream->flatten(int $dimensions = 1): Stream
$ data = [ 1 , [ 2 , 3 ], [ 4 , 5 ]];
$ result = Stream:: of ( $ data )
-> flatten ( $ mapper )
-> toArray ();
// [1, 2, 3, 4, 5] 流元素的頻率分佈。
$stream->frequencies(bool $strict = true): Stream
use IterTools Stream ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
$ result = Stream:: of ( $ grades )
-> frequencies ()
-> toAssociativeArray ();
// ['A' => 2, 'B' => 3, 'C' => 1] 通過公共數據元素返回流分組。
$stream->groupBy(callable $groupKeyFunction, callable $itemKeyFunction = null): Stream
$groupKeyFunction確定了組元素的關鍵。$itemKeyFunction允許每個組成員中的自定義索引。 use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ groups = Stream:: of ( $ input )
-> groupBy ( fn ( $ item ) => $ item > 0 ? ' positive ' : ' negative ' );
foreach ( $ groups as $ group => $ item ) {
// 'positive' => [1, 2, 3], 'negative' => [-1, -2, -3]
}永遠依次返回流通過流的元素。
$stream->infiniteCycle(): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> infiniteCycle ()
-> print ();
// 1, 2, 3, 1, 2, 3, ... 返回流與流與輸入迭代的流相交。
$stream->intersectionWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 , 4 , 5 , 6 , 7 , ' 8 ' , ' 9 ' ];
$ oddNumbers = [ 1 , 3 , 5 , 7 , 9 , 11 ];
$ stream = Stream:: of ( $ numbers )
-> intersectionWith ( $ numerics , $ oddNumbers )
-> toArray ();
// 3, 5, 7 返回使用類型脅迫的流與流與輸入迭代物相交的流。
$stream->intersectionCoerciveWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ languages = [ ' php ' , ' python ' , ' c++ ' , ' java ' , ' c# ' , ' javascript ' , ' typescript ' ];
$ scriptLanguages = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
$ stream = Stream:: of ( $ languages )
-> intersectionCoerciveWith ( $ scriptLanguages , $ supportsInterfaces )
-> toArray ();
// 'php', 'typescript' 將流返回到極限。
即使達到限制,也會停止更多數據。
$stream->limit(int $limit): Stream
Use IterTools Single ;
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ limit = 1 ;
$ goodMovies = Stream:: of ( $ matrixMovies )
-> limit ( $ limit )
-> toArray ();
// 'The Matrix' (and nothing else) 返回包含映射功能的結果的流到流的每個元素上。
$stream->map(callable $function): Stream
use IterTools Stream ;
$ grades = [ 100 , 95 , 98 , 89 , 100 ];
$ result = Stream:: of ( $ grades )
-> map ( fn ( $ grade ) => $ grade === 100 ? ' A ' : ' F ' )
-> toArray ();
// A, F, F, F, A 返回一對由流的元素組成的流。
$stream->pairwise(): Stream
返回空流(如果給定收集)包含少於2個元素。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ stream = Stream:: of ( $ input )
-> pairwise ()
-> toArray ();
// [1, 2], [2, 3], [3, 4], [4, 5] 將流與輸入迭代物部分相交的流部分返回。
$stream->partialIntersectionWith(int $minIntersectionCount, iterable ...$iterables): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 , 4 , 5 , 6 , 7 , ' 8 ' , ' 9 ' ];
$ oddNumbers = [ 1 , 3 , 5 , 7 , 9 , 11 ];
$ stream = Stream:: of ( $ numbers )
-> partialIntersectionWith ( $ numerics , $ oddNumbers )
-> toArray ();
// 1, 3, 4, 5, 6, 7, 9 使用類型的脅迫,將流部分與輸入迭代物相交的流部分相交。
$stream->partialIntersectionCoerciveWith(int $minIntersectionCount, iterable ...$iterables): Stream
use IterTools Stream ;
$ languages = [ ' php ' , ' python ' , ' c++ ' , ' java ' , ' c# ' , ' javascript ' , ' typescript ' ];
$ scriptLanguages = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
$ stream = Stream:: of ( $ languages )
-> partialIntersectionCoerciveWith ( 2 , $ scriptLanguages , $ supportsInterfaces )
-> toArray ();
// 'php', 'python', 'java', 'typescript', 'c#', 'javascript' 返回由密鑰索引函數重新索引的鍵值元素的新流。
$stream->reindex(callable $indexer): Stream
use IterTools Stream ;
$ data = [
[
' title ' => ' Star Wars: Episode IV – A New Hope ' ,
' episode ' => ' IV ' ,
' year ' => 1977 ,
],
[
' title ' => ' Star Wars: Episode V – The Empire Strikes Back ' ,
' episode ' => ' V ' ,
' year ' => 1980 ,
],
[
' title ' => ' Star Wars: Episode VI – Return of the Jedi ' ,
' episode ' => ' VI ' ,
' year ' => 1983 ,
],
];
$ reindexFunc = fn ( array $ swFilm ) => $ swFilm [ ' episode ' ];
$ reindexResult = Stream:: of ( $ data )
-> reindex ( $ reindexFunc )
-> toAssociativeArray ();
// [
// 'IV' => [
// 'title' => 'Star Wars: Episode IV – A New Hope',
// 'episode' => 'IV',
// 'year' => 1977,
// ],
// 'V' => [
// 'title' => 'Star Wars: Episode V – The Empire Strikes Back',
// 'episode' => 'V',
// 'year' => 1980,
// ],
// 'VI' => [
// 'title' => 'Star Wars: Episode VI – Return of the Jedi',
// 'episode' => 'VI',
// 'year' => 1983,
// ],
// ] 流元素的相對頻率分佈。
$stream->relativeFrequencies(bool $strict = true): Stream
use IterTools Stream ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
$ result = Stream:: of ( $ grades )
-> relativeFrequencies ()
-> toAssociativeArray ();
// A => 0.33, B => 0.5, C => 0.166 反轉流的元素。
$stream->reverse(): Stream
use IterTools Stream ;
$ words = [ ' are ' , ' you ' , ' as ' , ' bored ' , ' as ' , ' I ' , ' am ' ];
$ reversed = Stream:: of ( $ words )
-> reverse ()
-> toString ( ' ' );
// am I as bored as you are 返回流在流上累積運行平均值(平均值)的流。
$stream->runningAverage(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 3 , 5 ];
$ result = Stream:: of ( $ input )
-> runningAverage ()
-> toArray ();
// 1, 2, 3 返回流在流上累積運行差的流。
$stream->runningDifference(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningDifference ()
-> toArray ();
// -1, -3, -6, -10, -15 返回流在流上累積運行最大值的流。
$stream->runningMax(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> runningMax ()
-> toArray ();
// 1, 1, 2, 2, 3, 3 返回流在流上累積運行最小值的流。
$stream->runningMin(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> runningMin ()
-> toArray ();
// 1, -1, -1, -2, -2, -3 返回流在流中累積運行產品的流。
$stream->runningProduct(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningProduct ()
-> toArray ();
// 1, 2, 6, 24, 120 返回流在流上運行總數的流。
$stream->runningTotal(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningTotal ()
-> toArray ();
// 1, 3, 6, 10, 15 跳過流的一些元素。
$stream->skip(int $count, int $offset = 0): Stream
use IterTools Stream ;
$ movies = [
' The Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' The Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ onlyTheBest = Stream:: of ( $ movies )
-> skip ( 3 )
-> skip ( 3 , 3 )
-> toArray ();
// 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi' 提取流的切片。
$stream->slice(int $start = 0, int $count = null, int $step = 1)
use IterTools Stream ;
$ olympics = [ 1992 , 1994 , 1996 , 1998 , 2000 , 2002 , 2004 , 2006 , 2008 , 2010 , 2012 , 2014 , 2016 , 2018 , 2020 , 2022 ];
$ summerOlympics = Stream:: of ( $ olympics )
-> slice ( 0 , 8 , 2 )
-> toArray ();
// [1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020] 分類流。
$stream->sort(callable $comparator = null)
如果沒有提供比較器,則必須可比較峰值源的元素。
use IterTools Stream ;
$ input = [ 3 , 4 , 5 , 9 , 8 , 7 , 1 , 6 , 2 ];
$ result = Stream:: of ( $ input )
-> sort ()
-> toArray ();
// 1, 2, 3, 4, 5, 6, 7, 8, 9 返回流和給定迭代的對稱差的流。
$stream->symmetricDifferenceWith(iterable ...$iterables): Stream
注意:如果輸入迭代物產生重複的項目,則適用多發路交叉規則。
use IterTools Stream ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
$ stream = Stream:: of ( $ a )
-> symmetricDifferenceWith ( $ b , $ c )
-> toArray ();
// '1', 4, 5, 6, 7, 8, 9 使用類型的脅迫返回流和給定的迭代的對稱差的流。
$stream->symmetricDifferenceCoerciveWith(iterable ...$iterables): Stream
注意:如果輸入迭代物產生重複的項目,則適用多發路交叉規則。
use IterTools Stream ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
$ stream = Stream:: of ( $ a )
-> symmetricDifferenceCoerciveWith ( $ b , $ c )
-> toArray ();
// 4, 5, 6, 7, 8, 9 只要謂詞為真,將元素從流中保持。
$stream->takeWhile(callable $predicate): Stream
如果沒有提供謂詞,則使用數據的布爾值。
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> takeWhile ( fn ( $ value ) => abs ( $ value ) < 3 )
-> toArray ();
// 1, -1, 2, -2 返回由流和輸入迭代的集合的流。
$stream->unionWith(iterable ...$iterables): Stream
注意:如果輸入迭代物產生重複的項目,則適用多鍵聯合規則。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionWith ([ 3 , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] 返回使用類型脅迫的流和輸入迭代的流。
$stream->unionCoerciveWith(iterable ...$iterables): Stream
注意:如果輸入迭代物產生重複的項目,則適用多鍵聯合規則。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionCoerciveWith ([ ' 3 ' , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] 返回由同時流式流的多個峰值集成的流。
$stream->zipWith(iterable ...$iterables): Stream
對於不均勻的長度,當最短的峰值耗盡時,迭代就會停止。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipWith ([ 4 , 5 , 6 ])
-> zipWith ([ 7 , 8 , 9 ])
-> toArray ();
// [1, 4, 7], [2, 5, 8], [3, 6, 9] 返回由多個迭代集合組成的流,如果長度不相等,則使用默認填充物值。
$stream->zipFilledWith(mixed $default, iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipFilledWith ( ' ? ' , [ ' A ' , ' B ' ]);
foreach ( $ stream as $ zipped ) {
// [1, A], [2, B], [3, ?]
}返回由同時流的多個相等長度流的多個迭代集合的流。
$stream->zipEqualWith(iterable ...$iterables): Stream
工作類似於Stream::zipWith()方法,但是如果長度不相等,則拋出 lengthException,即至少一個迭代器在其他迭代之前結束。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipEqualWith ([ 4 , 5 , 6 ])
-> zipEqualWith ([ 7 , 8 , 9 ]);
foreach ( $ stream as $ zipped ) {
// [1, 4, 7], [2, 5, 8], [3, 6, 9]
}返回由同時流式流的多個峰值集成的流。
$stream->zipLongestWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ stream = Stream:: of ( $ input )
-> zipLongestWith ([ 4 , 5 , 6 ])
-> zipLongestWith ([ 7 , 8 , 9 , 10 ]);
foreach ( $ stream as $ zipped ) {
// [1, 4, 7], [2, 5, 8], [3, 6, 9], [4, null, 10], [null, null, 5]
}如果所有元素匹配謂詞功能,則返回true。
$stream->allMatch(callable $predicate): bool
use IterTools Summary ;
$ finalFantasyNumbers = [ 4 , 5 , 6 ];
$ isOnSuperNintendo = fn ( $ ff ) => $ ff >= 4 && $ ff <= 6 ;
$ boolean = Stream:: of ( $ finalFantasyNumbers )
-> allMatch ( $ isOnSuperNintendo );
// true 如果所有元素都是唯一的,則返回true。
$stream->allUnique(bool $strict = true): bool
默認為嚴格類型的比較。設置嚴格為false以進行類型的脅迫比較。
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Stream:: of ( $ items )
-> allUnique ();
// true 如果任何元素匹配謂詞函數,則返回true。
$stream->anyMatch(callable $predicate): bool
use IterTools Summary ;
$ answers = [ ' fish ' , ' towel ' , 42 , " don't panic " ];
$ isUltimateAnswer = fn ( $ a ) => a == 42 ;
$ boolean = Stream:: of ( $ answers )
-> anyMatch ( $ answers , $ isUltimateAnswer );
// true 如果所有迭代都是帶有流的排列,則返回true。
$stream->arePermutationsWith(...$iterables): bool
use IterTools Summary ;
$ rite = [ ' r ' , ' i ' , ' t ' , ' e ' ];
$ reit = [ ' r ' , ' e ' , ' i ' , ' t ' ];
$ tier = [ ' t ' , ' i ' , ' e ' , ' r ' ];
$ tire = [ ' t ' , ' i ' , ' r ' , ' e ' ];
$ trie = [ ' t ' , ' r ' , ' i ' , ' e ' ];
$ boolean = Stream:: of ([ ' i ' , ' t ' , ' e ' , ' r ' ])
-> arePermutationsWith ( $ rite , $ reit , $ tier , $ tire , $ trie );
// true 如果所有迭代都是帶有類型的脅迫的流的置換,則返回true。
$stream->arePermutationsCoerciveWith(...$iterables): bool
use IterTools Summary ;
$ set2 = [ 2.0 , ' 1 ' , 3 ];
$ set3 = [ 3 , 2 , 1 ];
$ boolean = Stream:: of ([ 1 , 2.0 , ' 3 ' ])
-> arePermutationsCoerciveWith ( $ set2 , $ set3 );
// true 返回為true,如果確切的n項根據謂詞功能為true。
$stream->exactlyN(int $n, callable $predicate = null): bool
use IterTools Summary ;
$ twoTruthsAndALie = [ true , true , false ];
$ n = 2 ;
$ boolean = Stream:: of ( $ twoTruthsAndALie )-> exactlyN ( $ n );
// true 如果流是空的,則返回true。
$stream->isEmpty(): bool
use IterTools Summary ;
$ numbers = [ 0 , 1 , 2 , 3 , 4 , 5 ];
$ filterFunc = fn ( $ x ) => $ x > 10 ;
$ boolean = Stream::( $ numbers )
-> filter ( $ filterFunc )
-> isEmpty ();
// true 如果給定集合的所有元素滿足謂詞的所有元素都出現在所有不滿意的元素之前,則返回為true。
$stream->isPartitioned(callable $predicate = null): bool
use IterTools Summary ;
$ numbers = [ 0 , 2 , 4 , 1 , 3 , 5 ];
$ evensBeforeOdds = fn ( $ item ) => $ item % 2 === 0 ;
$ boolean = Stream::( $ numbers )
-> isPartitioned ( $ evensBeforeOdds );
// true 如果以升序排序的源,則返回true;否則錯誤。
$stream->isSorted(): bool
具有可觀來源的項目必須是可比的。
如果源是空的,則返回true,或者只有一個元素。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> isSorted ();
// true
$ input = [ 1 , 2 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isSorted ();
// false 如果以相反的降序排序源,則返回true;否則錯誤。
$stream->isReversed(): bool
具有可觀來源的項目必須是可比的。
如果源是空的,則返回true,或者只有一個元素。
use IterTools Stream ;
$ input = [ 5 , 4 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isReversed ();
// true
$ input = [ 1 , 2 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isReversed ();
// false 如果沒有元素匹配謂詞函數,則返回true。
$stream->noneMatch(callable $predicate): bool
use IterTools Summary ;
$ grades = [ 45 , 50 , 61 , 0 ];
$ isPassingGrade = fn ( $ grade ) => $ grade >= 70 ;
$ boolean = Stream:: of ( $ grades )-> noneMatch ( $ isPassingGrade );
// true 返回返回的源,如果來源和所有給定的收藏量都是相同的。
$stream->sameWith(iterable ...$iterables): bool
對於空的迭代列表,返回true。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> sameWith ([ 1 , 2 , 3 , 4 , 5 ]);
// true
$ result = Stream:: of ( $ input )
-> sameWith ([ 5 , 4 , 3 , 2 , 1 ]);
// false 如果源源返回true,並且所有給定的集合具有相同的長度。
$stream->sameCountWith(iterable ...$iterables): bool
對於空的迭代列表,返回true。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> sameCountWith ([ 5 , 4 , 3 , 2 , 1 ]);
// true
$ result = Stream:: of ( $ input )
-> sameCountWith ([ 1 , 2 , 3 ]);
// false 將含義的源降低到其項目的平均值。
$stream->toAverage(): mixed
如果源為空,則返回null。
use IterTools Stream ;
$ input = [ 2 , 4 , 6 , 8 ];
$ result = Stream:: of ( $ iterable )
-> toAverage ();
// 5 將其長度降低到其長度。
$stream->toCount(): mixed
use IterTools Stream ;
$ input = [ 10 , 20 , 30 , 40 , 50 ];
$ result = Stream:: of ( $ iterable )
-> toCount ();
// 5 將峰值源簡化為第一個元素。
$stream->toFirst(): mixed
拋出LengthException如果源是空的。
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirst ();
// 10 將峰值源降低到其第一個和最後一個元素。
$stream->toFirstAndLast(): array{mixed, mixed}
拋出LengthException如果源是空的。
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirstAndLast ();
// [10, 30] 將含義的源降低到其最後一個元素。
$stream->toLast(): mixed
拋出LengthException如果源是空的。
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toLast ();
// 30 將其最大值降低到其最大值。
$stream->toMax(callable $compareBy = null): mixed
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。 use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMax ();
// 3 將含義的來源降低到其最小值。
$stream->toMin(callable $compareBy = null): mixed
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。 use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMin ();
// -3 將流減少到其上限和下邊界的陣列(最大和最小)。
$stream->toMinMax(callable $compareBy = null): array
$compareBy必須返回可比值。$compareBy則給定收集的項目必須是可比的。[null, null]如果給定收集為空。 use IterTools Stream ;
$ numbers = [ 1 , 2 , 7 , - 1 , - 2 , - 3 ];
[ $ min , $ max ] = Stream:: of ( $ numbers )
-> toMinMax ();
// [-3, 7] 將流降低到第n個位置的值。
$stream->toNth(int $position): mixed
如果源為空,則返回null。
use IterTools Stream ;
$ lotrMovies = [ ' The Fellowship of the Ring ' , ' The Two Towers ' , ' The Return of the King ' ];
$ result = Stream:: of ( $ lotrMovies )
-> toNth ( 2 );
// The Return of the King 將流到其物品的產品中。
$stream->toProduct(): mixed
如果源為空,則返回null。
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toProduct ();
// 120 將流降低到其中的隨機值。
$stream->toRandomValue(): mixed
use IterTools Stream ;
$ rpsHands = [ ' rock ' , ' paper ' , ' scissors ' ]
$ range = Stream:: of ( $ numbers )
-> map ( ' strtoupper ' )
-> toRandomValue ();
// e.g., rock 將流降低到其範圍(最大和最小之間的差異)。
$stream->toRange(): int|float
返回0如果源為空的源。
use IterTools Stream ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Stream:: of ( $ numbers )
-> toRange ();
// 20 還原為連接所有元素的字符串。
$stream->toString(string $separator = '', string $prefix = '', string $suffix = ''): string
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
$ string = Stream:: of ( $ words )-> toString ( $ words );
// IterToolsPHPv1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' );
// IterTools-PHP-v1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' , ' Library: ' );
// Library: IterTools-PHP-v1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' , ' Library: ' , ' ! ' );
// Library: IterTools-PHP-v1.0! 將尤多的來源降低到其項目的總和。
$stream->toSum(): mixed
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toSum ();
// 15 還原含量的源,例如array_reduce()函數。
但是與array_reduce()不同,它可以與所有iterable類型一起使用。
$stream->toValue(callable $reducer, mixed $initialValue): mixed
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toValue ( fn ( $ carry , $ item ) => $ carry + $ item );
// 15 返回流元素數組。
$stream->toArray(): array
use IterTools Stream ;
$ array = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
-> distinct ()
-> map ( fn ( $ x ) => $ x ** 2 )
-> toArray ();
// [1, 4, 9, 16, 25] 返回流元素的鍵值映射。
$stream->toAssociativeArray(callable $keyFunc, callable $valueFunc): array
use IterTools Stream ;
$ keyFunc
$ array = Stream:: of ([ ' message 1 ' , ' message 2 ' , ' message 3 ' ])
-> map ( ' strtoupper ' )
-> toAssociativeArray (
fn ( $ s ) => md5 ( $ s ),
fn ( $ s ) => $ s
);
// [3b3f2272b3b904d342b2d0df2bf31ed4 => MESSAGE 1, 43638d919cfb8ea31979880f1a2bb146 => MESSAGE 2, ... ] 返回幾個獨立(重複)流。
$stream->tee(int $count): array
use IterTools Transform ;
$ daysOfWeek = [ ' Mon ' , ' Tues ' , ' Wed ' , ' Thurs ' , ' Fri ' , ' Sat ' , ' Sun ' ];
$ count = 3 ;
[ $ week1Stream , $ week2Stream , $ week3Stream ] = Stream:: of ( $ daysOfWeek )
-> tee ( $ count );
// Each $weekStream contains ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'] 通過在流中的每個項目上進行可可執行操作。
$stream->callForEach(callable $function): void
use IterTools Stream ;
$ languages = [ ' PHP ' , ' Python ' , ' Java ' , ' Go ' ];
$ mascots = [ ' elephant ' , ' snake ' , ' bean ' , ' gopher ' ];
$ zipPrinter = fn ( $ zipped ) => print ( "{ $ zipped [ 0 ]} 's mascot: { $ zipped [ 1 ]}" );
Stream:: of ( $ languages )
-> zipWith ( $ mascots )
-> callForEach ( $ zipPrinter );
// PHP's mascot: elephant
// Python's mascot: snake
// ... 在流中打印每個項目。
$stream->print(string $separator = '', string $prefix = '', string $suffix = ''): void
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
Stream:: of ( $ words )-> print (); // IterToolsPHPv1.0
Stream:: of ( $ words )-> print ( ' - ' ); // IterTools-PHP-v1.0
Stream:: of ( $ words )-> print ( ' - ' , ' Library: ' ); // Library: IterTools-PHP-v1.0
Stream:: of ( $ words )-> print ( ' - ' , ' Library: ' , ' ! ' ); // Library: IterTools-PHP-v1.0! 在自己的行上打印流中的每個項目。
$stream->println(): void
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
Stream:: of ( $ words )-> printLn ();
// IterTools
// PHP
// v1.0 將流的內容寫入CSV文件。
$stream->toCsvFile(resource $fileHandle, array $header = null, string 'separator = ',', string $enclosure = '"', string $escape = '\'): void
use IterTools Stream ;
$ starWarsMovies = [
[ ' Star Wars: Episode IV – A New Hope ' , ' IV ' , 1977 ],
[ ' Star Wars: Episode V – The Empire Strikes Back ' , ' V ' , 1980 ],
[ ' Star Wars: Episode VI – Return of the Jedi ' , ' VI ' , 1983 ],
];
$ header = [ ' title ' , ' episode ' , ' year ' ];
Stream:: of ( $ data )
-> toCsvFile ( $ fh , $ header );
// title,episode,year
// "Star Wars: Episode IV – A New Hope",IV,1977
// "Star Wars: Episode V – The Empire Strikes Back",V,1980
// "Star Wars: Episode VI – Return of the Jedi",VI,1983 將流的內容寫入文件。
$stream->toFile(resource $fileHandle, string $newLineSeparator = PHP_EOL, string $header = null, string $footer = null): void
use IterTools Stream ;
$ data = [ ' item1 ' , ' item2 ' , ' item3 ' ];
$ header = ' <ul> ' ;
$ footer = ' </ul> ' ;
Stream:: of ( $ data )
-> map ( fn ( $ item ) => " <li> $ item </li> " )
-> toFile ( $ fh , PHP_EOL , $ header , $ footer );
// <ul>
// <li>item1</li>
// <li>item2</li>
// <li>item3</li>
// </ul>窺視其他流操作之間的每個元素,在不修改流的情況下執行一些操作。
$stream->peek(callable $callback): Stream
use IterTools Stream ;
$ logger = new SimpleLog Logger ( ' /tmp/log.txt ' , ' iterTools ' );
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peek ( fn ( $ x ) => $ logger -> info ( $ x ))
-> foreach ( $ someComplexCallable );窺視其他流操作之間的整個流以在不修改流的情況下執行一些操作。
$stream->peekStream(callable $callback): Stream
use IterTools Stream ;
$ logger = new SimpleLog Logger ( ' /tmp/log.txt ' , ' iterTools ' );
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekStream ( fn ( $ stream ) => $ logger -> info ( $ stream ))
-> foreach ( $ someComplexCallable );窺視其他流操作之間的每個元素以打印每個項目而不修改流。
$stream->peekPrint(string $separator = '', string $prefix = '', string $suffix = ''): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrint ()
-> foreach ( $ someComplexCallable );窺視其他流操作之間的每個元素以print_r每個項目,而無需修改流。
$stream->peekPrintR(callable $callback): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrintR ()
-> foreach ( $ someComplexCallable ); print_r流中的每個項目。
$stream->printR(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> printR ();
// print_r output var_dump流中的每個項目。
$stream->varDump(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> varDump ();
// var_dump output 可以將Itertools組合起來,以創建新的峰值構圖。
use IterTools Multi ;
use IterTools Single ;
$ letters = ' ABCDEFGHI ' ;
$ numbers = ' 123456789 ' ;
foreach (Multi:: zip (Single:: string ( $ letters ), Single:: string ( $ numbers )) as [ $ letter , $ number ]) {
$ battleshipMove = new BattleshipMove( $ letter , $ number )
}
// A1, B2, C3 use IterTools Multi ;
use IterTools Single ;
$ letters = ' abc ' ;
$ numbers = ' 123 ' ;
foreach (Multi:: chain (Single:: string ( $ letters ), Single:: string ( $ numbers )) as $ character ) {
print ( $ character );
}
// a, b, c, 1, 2, 3 當有選項時,默認值將進行嚴格的類型比較:
當可以使用可選標誌的脅迫類型(非刻板類型)時:
Itertools PHP符合以下標準:
Itertools PHP已獲得MIT許可證的許可。
Itertools功能不僅限於PHP和Python。其他語言具有相似的庫。熟悉的功能在其他語言工作時可用。