
Pythonに触発されました - PHPのために設計されています。
Itertoolsは、2種類のツールを提供することにより、あなたに反復スーパースターになります。
ループイテレーションツールの例
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 | Falsy Elementsのフィルター | Single::filterFalse($data) |
filterKeys | 述語が真であるキーをフィルターします | 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 | イテレーターにiterableを変換します | Transform::toIterator($data) |
| まとめ | 説明 | コードスニペット |
|---|---|---|
allMatch | すべてのアイテムが述語に応じて真である場合はtrue | Summary::allMatch($data, $predicate) |
allUnique | すべてのアイテムが一意である場合はtrue | Summary::allUnique($data, [$strict]) |
anyMatch | PRESTICEに従って、項目が真である場合はTRUE | Summary::anyMatch($data, $predicate) |
arePermutations | iterablesが互いの順列である場合はtrue | Summary::arePermutations(...$iterables) |
arePermutationsCoercive | iterablesがタイプの強制で互いの順列である場合真実 | Summary::arePermutationsCoercive(...$iterables) |
exactlyN | 正確にnアイテムが前のものに応じてtrueが真である場合はtrue | Summary::exactlyN($data, $n, $predicate) |
isEmpty | iterableにアイテムがない場合はtrue | Summary::isEmpty($data) |
isPartitioned | 他の人の前に述語に応じて真のアイテムとパーティション化されている場合はtrue | Summary::isPartitioned($data, $predicate) |
isSorted | iterableソートがある場合はtrue | Summary::isSorted($data) |
isReversed | iterable reverseソートがある場合はtrue | Summary::isReversed($data) |
noneMatch | PRESTICEによると、項目が真実でない場合はTRUE | Summary::noneMatch($data, $predicate) |
same | iterablesが同じ場合はtrue | Summary::same(...$iterables) |
sameCount | true iterablesの長さが同じ場合 | 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 | 予測機能が真である間に、反復可能なソースから要素をドロップする | $stream->dropWhile($predicate) |
filter | 述語関数が真である要素のみをフィルタリングします | $stream->filterTrue($predicate) |
filterTrue | 真実の要素のみをフィルタリングします | $stream->filterTrue() |
filterFalse | Falsy要素のみをフィルターします | $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 | 述語が真である限り、反復可能なソースから要素を返す | $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 | ストリームのすべてのiterablesの順列がある場合、trueを返します | $stream->arePermutationsWith(...$iterables) |
arePermutationsCoerciveWith | タイプの強制を伴うストリームのすべての繰り返しの順列が真実である場合にtrueを返します | $stream->arePermutationsCoerciveWith(...$iterables) |
exactlyN | PRESTICESに従って正確にnアイテムが真である場合にtrueを返します | $stream->exactlyN($n, $predicate) |
isEmpty | ストリームにアイテムがない場合、trueを返します | $stream::isEmpty() |
isPartitioned | 他の人の前に述語に応じて真のアイテムと分割された場合にtrueを返します | $stream::isPartitioned($predicate) |
isSorted | ストリームが昇順でソートされている場合、trueを返します | $stream->isSorted() |
isReversed | ストリームが逆の降順でソートされている場合、trueを返します | $stream->isReversed() |
noneMatch | ストリームのアイテムがいかなるものもない場合にtrueを返しますPredicate | $stream->noneMatch($predicate) |
sameWith | ストリームとすべての指定されたコレクションが同じ場合真実を返します | $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 | nth位置でストリームを値に減らします | $stream->toNth($position) |
toProduct | ストリームをアイテムの製品に削減します | $stream->toProduct() |
toString | Streamを結合した文字列に減らします | $stream->toString([$separator], [$prefix], [$suffix]) |
toSum | ストリームをアイテムの合計に減らします | $stream->toSum() |
toRandomValue | ストリームを削減し、その中のランダム値になります | $stream->toRandomValue() |
toRange | ストリームを最大値とMIN値の差に減らします | $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 | 操作間でprint-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は、複数の反復可能な入力で動作しますが、2つだけに制限されていません。
$ 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をスローします。つまり、少なくとも1つのイテレーターが他の繰り返しの前に終了します。
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述語関数が真であるキーを持つ反復可能な返品要素からの要素を除外します。
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オプションのオフセットオフセットの後、反復可能な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とは異なる)が最終的に戻ってくる場合でも、述語がfalseを返すとすぐに反復を停止します。
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)
入力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)
入力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-Partial交差点を反復します。
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タイプ強制を使用して、反復可能性のM部分的な交差を反復します。
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が複製アイテムを生成する場合、マルチセットの違いルールが適用されます。
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が複製アイテムを生成する場合、マルチセットの違いルールが適用されます。
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)
入力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)
入力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すべての反復可能性が互いの順列である場合、真実を返します。
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すべてのiterablesがタイプの強制を伴う互いの順列である場合、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述語関数に従って正確に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を返します。
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を返します。
単一の繰り返しまたは空のiterablesリストは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を返します。
単一の繰り返しまたは空のiterablesリストは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
// ]上限と下限の配列(最大およびmin)に減少します。
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
iterableソースが空の場合は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 ストリームは、操作のパイプラインを通じて配列と反復性を変換するための流fluentインターフェイスを提供します。
ストリームは次のとおりです。
$ 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, 追加のソースを連鎖させてストリームを1つの連続したストリームに戻します。
$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
セレクターは、どのデータを示します。真の値はアイテムを選択します。 false値はデータをフィルターアウトします。
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 falsyの要素のみを保持するストリームから要素を除外します。
$stream->filterFalse(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterFalse ()
-> toArray ();
// 0, 0 キー上の述語関数がtrueの場合、要素のみを維持するストリームから要素を除外します。
$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 runningランニングマックスをストリームに蓄積するストリームを返します。
$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
注:入力Iterablesが複製アイテムを生成する場合、マルチセット交差点ルールが適用されます。
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
注:入力Iterablesが複製アイテムを生成する場合、マルチセット交差点ルールが適用されます。
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
注:入力iterablesが重複アイテムを生成する場合、マルチセットユニオンルールが適用されます。
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
注:入力iterablesが重複アイテムを生成する場合、マルチセットユニオンルールが適用されます。
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 すべてのiterablesがストリームの順列である場合、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 すべてのiterablesがタイプの強制を備えたストリームの順列である場合、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 述語関数に従って正確に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を返します。それ以外の場合はfalse。
$stream->isSorted(): bool
反復可能なソースのアイテムは同等でなければなりません。
iterableソースが空であるか、要素が1つしかない場合、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 iterableソースが逆の降順でソートされている場合、trueを返します。それ以外の場合はfalse。
$stream->isReversed(): bool
反復可能なソースのアイテムは同等でなければなりません。
iterableソースが空であるか、要素が1つしかない場合、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 iterableソースとすべての指定されたコレクションが同じ場合、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 iterableソースとすべての指定されたコレクションが同じ長さの場合、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
iterableソースが空である場合、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
iterableソースが空である場合、 LengthExceptionをスローします。
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirst ();
// 10 反復可能なソースを最初と最後の要素に減らします。
$stream->toFirstAndLast(): array{mixed, mixed}
iterableソースが空である場合、 LengthExceptionをスローします。
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirstAndLast ();
// [10, 30] 反復可能なソースをその最後の要素に減らします。
$stream->toLast(): mixed
iterableソースが空である場合、 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 ストリームを上限と下限の配列(最大およびmin)に減らします。
$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] NTH位置でのストリームを値に減らします。
$stream->toNth(int $position): mixed
iterableソースが空である場合、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
iterableソースが空である場合、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
iterableソースが空の場合は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 functionality is not limited to PHP and Python. Other languages have similar libraries. Familiar functionality is available when working in other languages.