
Inspirado em Python - projetado para PHP.
O ITERTOOLS faz de você uma estrela de iteração, fornecendo dois tipos de ferramentas:
Exemplo de ferramentas de iteração de loop
foreach (Multi:: zip ([ ' a ' , ' b ' ], [ 1 , 2 ]) as [ $ letter , $ number ]) {
print ( $ letter . $ number ); // a1, b2
}Exemplo de ferramentas de iteração de fluxo
$ 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 Todas as funções funcionam em coleções iterable :
array (tipo)Generator (tipo)Iterator (interface)Traversable (interface)| Iterador | Descrição | Trenó de código |
|---|---|---|
chain | Cadeia múltipla de iterables juntos | Multi::chain($list1, $list2) |
zip | Itera várias coleções simultaneamente até o mais curto iterador concluir | Multi::zip($list1, $list2) |
zipEqual | Itera várias coleções de igual comprimento simultaneamente, erro se não for igual | Multi::zipEqual($list1, $list2) |
zipFilled | Itera várias coleções, usando um valor de preenchimento se os comprimentos não forem iguais | Multi::zipFilled($default, $list1, $list2) |
zipLongest | Itera várias coleções simultaneamente até o iterador mais longo completar | Multi::zipLongest($list1, $list2) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
chunkwise | Itera por pedaços | Single::chunkwise($data, $chunkSize) |
chunkwiseOverlap | Itera por pedaços sobrepostos | Single::chunkwiseOverlap($data, $chunkSize, $overlapSize) |
compress | Filtre os elementos não selecionados | Single::compress($data, $selectors) |
compressAssociative | Filtrar elementos por chaves não selecionadas | Single::compressAssociative($data, $selectorKeys) |
dropWhile | Soltar elementos enquanto o predicado é verdadeiro | Single::dropWhile($data, $predicate) |
filter | Filtro para elementos onde o predicado é verdadeiro | Single::filterTrue($data, $predicate) |
filterTrue | Filtro para elementos verdadeiros | Single::filterTrue($data) |
filterFalse | Filtro para elementos falsamente | Single::filterFalse($data) |
filterKeys | Filtro para chaves onde o predicado é verdadeiro | Single::filterKeys($data, $predicate) |
flatMap | Função do mapa em itens e resultado de achatar | Single::flaMap($data, $mapper) |
flatten | Iterável multidimensional achatado | Single::flatten($data, [$dimensions]) |
groupBy | Dados do grupo por um elemento comum | Single::groupBy($data, $groupKeyFunction, [$itemKeyFunc]) |
limit | Itera até um limite | Single::limit($data, $limit) |
map | Função de mapa em cada item | Single::map($data, $function) |
pairwise | Itera pares sucessivos sobrepostos | Single::pairwise($data) |
reindex | Chaves de reindex do valor-chave iterável | Single::reindex($data, $reindexer) |
repeat | Repita um item várias vezes | Single::repeat($item, $repetitions) |
reverse | Itera elementos em ordem inversa | Single::reverse($data) |
skip | Itera depois de pular elementos | Single::skip($data, $count, [$offset]) |
slice | Extraia uma fatia do iterável | Single::slice($data, [$start], [$count], [$step]) |
string | Itera os personagens de uma corda | Single::string($string) |
takeWhile | Elementos itera enquanto o predicado é verdadeiro | Single::takeWhile($data, $predicate) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
count | Conte sequencialmente para sempre | Infinite::count($start, $step) |
cycle | Ciclo através de uma coleção | Infinite::cycle($collection) |
repeat | Repita um item para sempre | Infinite::repeat($item) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
choice | Seleções aleatórias da lista | Random::choice($list, $repetitions) |
coinFlip | Moedas aleatórias (0 ou 1) | Random::coinFlip($repetitions) |
number | Números aleatórios | Random::number($min, $max, $repetitions) |
percentage | Porcentagem aleatória entre 0 e 1 | Random::percentage($repetitions) |
rockPaperScissors | Hands aleatórias de paper-tesores | Random::rockPaperScissors($repetitions) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
frequencies | Distribuição de frequência dos dados | Math::frequencies($data, [$strict]) |
relativeFrequencies | Distribuição de frequência relativa dos dados | Math::relativeFrequencies($data, [$strict]) |
runningAverage | Acumulação média em execução | Math::runningAverage($numbers, $initialValue) |
runningDifference | Acumulação de diferença de execução | Math::runningDifference($numbers, $initialValue) |
runningMax | Executando acumulação máxima | Math::runningMax($numbers, $initialValue) |
runningMin | Executando acumulação mínima | Math::runningMin($numbers, $initialValue) |
runningProduct | Executando o acúmulo de produtos | Math::runningProduct($numbers, $initialValue) |
runningTotal | Executando acumulação total | Math::runningTotal($numbers, $initialValue) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
distinct | Itera apenas itens distintos | Set::distinct($data) |
distinctBy | Itera apenas itens distintos usando comparador personalizado | Set::distinct($data, $compareBy) |
intersection | Interseção de iteráveis | Set::intersection(...$iterables) |
intersectionCoercive | Interseção com coerção de tipo | Set::intersectionCoercive(...$iterables) |
partialIntersection | Interseção parcial de iteráveis | Set::partialIntersection($minCount, ...$iterables) |
partialIntersectionCoercive | Interseção parcial com coerção de tipo | Set::partialIntersectionCoercive($minCount, ...$iterables) |
symmetricDifference | Diferença simétrica de iteráveis | Set::symmetricDifference(...$iterables) |
symmetricDifferenceCoercive | Diferença simétrica com coerção de tipo | Set::symmetricDifferenceCoercive(...$iterables) |
union | Union of Iterables | Set::union(...$iterables) |
unionCoercive | União com coerção de tipo | Set::unionCoercive(...$iterables) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
asort | Itera uma coleção classificada mantendo chaves | Sort::asort($data, [$comparator]) |
sort | Itera uma coleção classificada | Sort::sort($data, [$comparator]) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
readCsv | Interseção Uma linha de arquivo CSV por linha | File::readCsv($fileHandle) |
readLines | Itera uma linha de arquivo por linha | File::readLines($fileHandle) |
| Iterador | Descrição | Trenó de código |
|---|---|---|
tee | Iteradores de iteração duplicados | Transform::tee($data, $count) |
toArray | Transforme iterável para uma matriz | Transform::toArray($data) |
toAssociativeArray | Transforme iterável para uma matriz associativa | Transform::toAssociativeArray($data, [$keyFunc], [$valueFunc]) |
toIterator | Transforme iterável para um iterador | Transform::toIterator($data) |
| Resumo | Descrição | Trenó de código |
|---|---|---|
allMatch | Verdadeiro se todos os itens forem verdadeiros de acordo com o predicado | Summary::allMatch($data, $predicate) |
allUnique | Verdadeiro se todos os itens forem únicos | Summary::allUnique($data, [$strict]) |
anyMatch | Verdadeiro se algum item for verdadeiro de acordo com o predicado | Summary::anyMatch($data, $predicate) |
arePermutations | Verdadeiro se os iteráveis forem permutações um do outro | Summary::arePermutations(...$iterables) |
arePermutationsCoercive | Verdadeiro se os iteráveis forem permutações um do outro com coerção de tipo | Summary::arePermutationsCoercive(...$iterables) |
exactlyN | Verdadeiro se exatamente n itens são verdadeiros de acordo com o predicado | Summary::exactlyN($data, $n, $predicate) |
isEmpty | Verdadeiro se Iterable não tiver itens | Summary::isEmpty($data) |
isPartitioned | Verdadeiro se particionado com itens verdadeiros de acordo com o predicado diante de outros | Summary::isPartitioned($data, $predicate) |
isSorted | Verdade se iterável classificada | Summary::isSorted($data) |
isReversed | Verdadeiro, se iterável, classificado | Summary::isReversed($data) |
noneMatch | Verdadeiro se nenhum dos itens é verdadeiro de acordo com o predicado | Summary::noneMatch($data, $predicate) |
same | Verdadeiro se os iteráveis forem iguais | Summary::same(...$iterables) |
sameCount | Verdadeiro se os iteráveis tiverem os mesmos comprimentos | Summary::sameCount(...$iterables) |
| Redutor | Descrição | Trenó de código |
|---|---|---|
toAverage | Média média de elementos | Reduce::toAverage($numbers) |
toCount | Reduza para o comprimento do iterável | Reduce::toCount($data) |
toFirst | Reduza ao seu primeiro valor | Reduce::toFirst($data) |
toFirstAndLast | Reduza para seus primeiros e últimos valores | Reduce::toFirstAndLast($data) |
toLast | Reduza ao seu último valor | Reduce::toLast() |
toMax | Reduza para o seu maior elemento | Reduce::toMax($numbers, [$compareBy]) |
toMin | Reduza para o seu menor elemento | Reduce::toMin($numbers, [$compareBy]) |
toMinMax | Reduza para a matriz de limites superior e inferior | Reduce::toMinMax($numbers, [$compareBy]) |
toNth | Reduza para o valor na néssea | Reduce::toNth($data, $position) |
toProduct | Reduza para o produto de seus elementos | Reduce::toProduct($numbers) |
toRandomValue | Reduza para o valor aleatório de Iterable | Reduce::toRandomValue($data) |
toRange | Reduza para a diferença de valores max e min | Reduce::toRange($numbers) |
toString | Reduza para a corda unida | Reduce::toString($data, [$separator], [$prefix], [$suffix]) |
toSum | Reduza para a soma de seus elementos | Reduce::toSum($numbers) |
toValue | Reduza para valorizar usando redutor chamável | Reduce::toValue($data, $reducer, $initialValue) |
| Fonte | Descrição | Trenó de código |
|---|---|---|
of | Crie um fluxo de um iterável | Stream::of($iterable) |
ofCoinFlips | Crie um fluxo de movimentos aleatórios | Stream::ofCoinFlips($repetitions) |
ofCsvFile | Crie um fluxo a partir de um arquivo CSV | Stream::ofCsvFile($fileHandle) |
ofEmpty | Crie um fluxo vazio | Stream::ofEmpty() |
ofFileLines | Crie um fluxo de linhas de um arquivo | Stream::ofFileLines($fileHandle) |
ofRandomChoice | Crie um fluxo de seleções aleatórias | Stream::ofRandomChoice($items, $repetitions) |
ofRandomNumbers | Crie um fluxo de números aleatórios (números inteiros) | Stream::ofRandomNumbers($min, $max, $repetitions) |
ofRandomPercentage | Crie um fluxo de porcentagens aleatórias entre 0 e 1 | Stream::ofRandomPercentage($repetitions) |
ofRange | Crie um fluxo de uma variedade de números | Stream::ofRange($start, $end, $step) |
ofRockPaperScissors | Crie um fluxo de mãos de paper-tesouro | Stream::ofRockPaperScissors($repetitions) |
| Operação | Descrição | Trenó de código |
|---|---|---|
asort | Classifica a fonte iterável mantendo as chaves | $stream->asort([$comparator]) |
chainWith | Fonte iterável em cadeia com itens juntos em uma única iteração | $stream->chainWith(...$iterables) |
compress | Compressa a fonte filtrando dados não selecionados | $stream->compress($selectors) |
compressAssociative | Compressa a fonte filtrando as teclas não selecionadas | $stream->compressAssociative($selectorKeys) |
chunkwise | Itera por pedaços | $stream->chunkwise($chunkSize) |
chunkwiseOverlap | Itera por pedaços sobrepostos | $stream->chunkwiseOverlap($chunkSize, $overlap) |
distinct | Filtre os elementos: iterar apenas itens exclusivos | $stream->distinct([$strict]) |
distinctBy | Filtre os elementos: iterar apenas itens exclusivos usando comparador personalizado | $stream->distinct($compareBy) |
dropWhile | Soltar elementos da fonte iterável enquanto a função de predicado é verdadeira | $stream->dropWhile($predicate) |
filter | Filtrar apenas elementos em que a função de predicado é verdadeira | $stream->filterTrue($predicate) |
filterTrue | Filtro apenas para elementos verdadeiros | $stream->filterTrue() |
filterFalse | Filtrar apenas elementos falsamente | $stream->filterFalse() |
filterKeys | Filtro para chaves onde a função predicada é verdadeira | $stream->filterKeys($predicate) |
flatMap | Função de mapa em elementos e resultado de achatado | $stream->flatMap($function) |
flatten | Fluxo multidimensional achatado | $stream->flatten($dimensions) |
frequencies | Distribuição de frequência | $stream->frequencies([$strict]) |
groupBy | Grupo Iterable Source por um elemento de dados comum | $stream->groupBy($groupKeyFunction, [$itemKeyFunc]) |
infiniteCycle | Percorrer os elementos da fonte iterável sequencialmente para sempre | $stream->infiniteCycle() |
intersectionWith | Intersect Iterable Source e recebeu iteráveis | $stream->intersectionWith(...$iterables) |
intersection CoerciveWith | Intersect Iterable Source e dado ites com coerção de tipo | $stream->intersectionCoerciveWith(...$iterables) |
limit | Limitar a iteração do fluxo | $stream->limit($limit) |
map | Função do mapa em elementos | $stream->map($function) |
pairwise | Retornar pares de elementos da fonte iterável | $stream->pairwise() |
partialIntersectionWith | Parcialmente interceptar a fonte iterável e receber iteráveis | $stream->partialIntersectionWith( $minIntersectionCount, ...$iterables) |
partialIntersection CoerciveWith | Fonte parcialmente intercepta e dada a coerção iterável com coerção de tipo | $stream->partialIntersectionCoerciveWith( $minIntersectionCount, ...$iterables) |
reindex | Chaves de reindex do fluxo de valor-chave | $stream->reindex($reindexer) |
relativeFrequencies | Distribuição de frequência relativa | $stream->relativeFrequencies([$strict]) |
reverse | Elementos reversos do fluxo | $stream->reverse() |
runningAverage | Acumule a média de corrida (média) sobre a fonte iterável | $stream->runningAverage($initialValue) |
runningDifference | Acumule a diferença de execução sobre a fonte iterável | $stream->runningDifference($initialValue) |
runningMax | Acumule o máximo em execução sobre a fonte iterável | $stream->runningMax($initialValue) |
runningMin | Acumule a fonte de corrida sobre a fonte iterável | $stream->runningMin($initialValue) |
runningProduct | Acumule o produto em execução sobre a fonte iterável | $stream->runningProduct($initialValue) |
runningTotal | Acumule o total em execução sobre a fonte iterável | $stream->runningTotal($initialValue) |
skip | Pule alguns elementos do fluxo | $stream->skip($count, [$offset]) |
slice | Extraia uma fatia do fluxo | $stream->slice([$start], [$count], [$step]) |
sort | Classifica o fluxo | $stream->sort([$comparator]) |
symmetricDifferenceWith | Diferença simétrica de fonte iterável e dado iterables | $this->symmetricDifferenceWith(...$iterables) |
symmetricDifference CoerciveWith | Diferença simétrica da fonte iterável e dado iterables com coerção de tipo | $this->symmetricDifferenceCoerciveWith( ...$iterables) |
takeWhile | Retornar elementos da fonte iterável, desde que o predicado seja verdadeiro | $stream->takeWhile($predicate) |
unionWith | União do fluxo com iterables | $stream->unionWith(...$iterables) |
unionCoerciveWith | União de fluxo com iterables com coerção de tipo | $stream->unionCoerciveWith(...$iterables) |
zipWith | Itera a fonte iterável com outra coleção iterável simultaneamente | $stream->zipWith(...$iterables) |
zipEqualWith | Itera fonte iterável com outra coleção iterável de comprimentos iguais simultaneamente | $stream->zipEqualWith(...$iterables) |
zipFilledWith | Itera fonte iterável com outra coleção iterável usando o enchimento padrão | $stream->zipFilledWith($default, ...$iterables) |
zipLongestWith | Itera a fonte iterável com outra coleção iterável simultaneamente | $stream->zipLongestWith(...$iterables) |
| Operação terminal | Descrição | Trenó de código |
|---|---|---|
allMatch | Retorna True se todos os itens no Predicado de correspondência de fluxo | $stream->allMatch($predicate) |
allUnique | Retorna verdadeiro se todos os itens no fluxo forem únicos | $stream->allUnique([$strict]]) |
anyMatch | Retorna true se algum item no fluxo corresponde ao predicado | $stream->anyMatch($predicate) |
arePermutationsWith | Retorna True se todas as permutações iteáveis do fluxo | $stream->arePermutationsWith(...$iterables) |
arePermutationsCoerciveWith | Retorna True se todas as permutações itlesas de fluxo com coerção de tipo | $stream->arePermutationsCoerciveWith(...$iterables) |
exactlyN | Retorna verdadeiro se exatamente n itens forem verdadeiros de acordo com o predicado | $stream->exactlyN($n, $predicate) |
isEmpty | Retorna true se o fluxo não tiver itens | $stream::isEmpty() |
isPartitioned | Retorna true se particionado com itens true de acordo com o predicado diante de outros | $stream::isPartitioned($predicate) |
isSorted | Retorna true se o fluxo for classificado em ordem crescente | $stream->isSorted() |
isReversed | Retorna true se o fluxo for classificado em ordem descendente reversa | $stream->isReversed() |
noneMatch | Retorna True se nenhum dos itens no Predicado de correspondência de fluxo | $stream->noneMatch($predicate) |
sameWith | Retorna true se o fluxo e todas as coleções dadas são iguais | $stream->sameWith(...$iterables) |
sameCountWith | Retorna true se o fluxo e todas as coleções dadas têm os mesmos comprimentos | $stream->sameCountWith(...$iterables) |
| Operação terminal | Descrição | Trenó de código |
|---|---|---|
toAverage | Reduz o fluxo para a média média de seus itens | $stream->toAverage() |
toCount | Reduz o fluxo ao seu comprimento | $stream->toCount() |
toFirst | Reduz o fluxo ao seu primeiro valor | $stream->toFirst() |
toFirstAndLast | Reduz o fluxo para seus primeiros e últimos valores | $stream->toFirstAndLast() |
toLast | Reduz o fluxo ao seu último valor | $stream->toLast() |
toMax | Reduz o fluxo ao seu valor máximo | $stream->toMax([$compareBy]) |
toMin | Reduz o fluxo ao seu valor mínimo | $stream->toMin([$compareBy]) |
toMinMax | Reduz o fluxo para a matriz de limites superior e inferior | $stream->toMinMax([$compareBy]) |
toNth | Reduz o fluxo para valor | $stream->toNth($position) |
toProduct | Reduz o fluxo para o produto de seus itens | $stream->toProduct() |
toString | Reduz o fluxo para a corda unida | $stream->toString([$separator], [$prefix], [$suffix]) |
toSum | Reduz o fluxo para a soma de seus itens | $stream->toSum() |
toRandomValue | Reduz o fluxo para valor aleatório dentro dele | $stream->toRandomValue() |
toRange | Reduz o fluxo para a diferença de valores max e min | $stream->toRange() |
toValue | Reduz o fluxo como a função Array_Reduce () | $stream->toValue($reducer, $initialValue) |
| Operação terminal | Descrição | Trenó de código |
|---|---|---|
toArray | Retorna a matriz de elementos de fluxo | $stream->toArray() |
toAssociativeArray | Retorna o mapa do valor-chave dos elementos do fluxo | $stream->toAssociativeArray($keyFunc, $valueFunc) |
tee | Retorna a matriz de múltiplos fluxos idênticos | $stream->tee($count) |
| Operação terminal | Descrição | Trenó de código |
|---|---|---|
callForEach | Executar ação via função em cada item | $stream->callForEach($function) |
print | print cada item no fluxo | $stream->print([$separator], [$prefix], [$suffix]) |
printLn | print cada item em uma nova linha | $stream->printLn() |
toCsvFile | Escreva o conteúdo do fluxo em um arquivo CSV | $stream->toCsvFile($fileHandle, [$headers]) |
toFile | Escreva o conteúdo do fluxo em um arquivo | $stream->toFile($fileHandle) |
| Operação de depuração | Descrição | Trenó de código |
|---|---|---|
peek | Espreite em cada elemento entre operações de fluxo | $stream->peek($peekFunc) |
peekStream | Veja em todo o fluxo entre operações | $stream->peekStream($peekFunc) |
peekPrint | Espiar em cada elemento imprimindo entre operações | $stream->peekPrint() |
peekPrintR | Veja em cada elemento fazendo impressão-r entre operações | $stream->peekPrintR() |
printR | print_r cada item | $stream->printR() |
varDump | var_dump cada item | $stream->varDump() |
Adicione a biblioteca ao seu arquivo composer.json em seu projeto:
{
"require" : {
"markrogoyski/itertools-php" : " 1.* "
}
}Use o Composer para instalar a biblioteca:
$ php composer.phar installO compositor instalará o itertools dentro da pasta do fornecedor. Em seguida, você pode adicionar o seguinte aos seus arquivos .php para usar a biblioteca com o carregamento automático.
require_once __DIR__ . ' /vendor/autoload.php ' ;Como alternativa, use o Composer na linha de comando para exigir e instalar o itertools:
$ php composer.phar require markrogoyski/itertools-php:1.*
Todas as funções funcionam em coleções iterable :
array (tipo)Generator (tipo)Iterator (interface)Traversable (interface) Cadeia múltipla iterables juntos em uma única sequência contínua.
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'Itera várias coleções iteráveis simultaneamente.
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.
// ...O ZIP funciona com múltiplas entradas iteráveis-não limitadas a apenas duas.
$ 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 );
}Nota: Para comprimentos irregulares, a iteração para quando o mais curto iterável está esgotado.
Itera várias coleções iteráveis com comprimentos iguais simultaneamente.
Lança LengthException Se os comprimentos não são iguais, o que significa que pelo menos um iterador termina diante dos outros.
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]
}Itera várias coleções iteráveis simultaneamente, usando um valor de preenchimento padrão se os comprimentos não forem iguais.
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]
}Itera várias coleções iteráveis simultaneamente.
Multi::zipLongest(iterable ...$iterables)
Para comprimentos irregulares, os iteáveis exaustos produzirão null para as iterações restantes.
use IterTools Multi ;
$ letters = [ ' A ' , ' B ' , ' C ' ];
$ numbers = [ 1 , 2 ];
foreach (Multi:: zipLongest ( $ letters , $ numbers ) as [ $ letter , $ number ]) {
// ['A', 1], ['B', 2], ['C', null]
}Retornar elementos em pedaços de um determinado tamanho.
Single::chunkwise(iterable $data, int $chunkSize)
O tamanho do pedaço deve ser pelo menos 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]'
// ]Retornar pedaços de elementos sobrepostos.
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]
}Compressa um iterável filtrando dados que não estão selecionados.
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'Compressa um iterável filtrando as teclas que não são selecionadas.
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 JediSoltar elementos do iterável enquanto a função de predicado é verdadeira.
Depois que a função predicada retorna falsa uma vez, todos os elementos restantes são retornados.
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, 90Filtre os elementos dos elementos iteráveis apenas retornando onde a função de predicado é verdadeira.
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, 7Filtre os elementos dos elementos iteáveis apenas que retornam que são verdadeiros.
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, 94Filtre os elementos dos elementos iteráveis apenas retornando em que a função de predicado é falsa.
Se nenhum predicado for fornecido, o valor booleano dos dados será usado.
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, 0Filtre os elementos dos elementos de retorno iterable apenas para os quais as chaves a função de predicado é verdadeira.
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: TokyoMapeie uma função apenas os elementos do iterável e depois achate os resultados.
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 -5Achate um iterável multidimensional.
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]Dados do grupo por um elemento de dados comum.
Single::groupBy(iterable $data, callable $groupKeyFunction, callable $itemKeyFunction = null)
$groupKeyFunction determina a chave para agrupar elementos por.$itemKeyFunction opcional permite índices personalizados dentro de cada membro do grupo. 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'],
*/Itera até um limite.
Paradas mesmo que mais dados disponíveis se o limite atingido.
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)Mapeie uma função em cada elemento.
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, ARetorna pares sucessivos sobrepostos.
Retorna o gerador vazio se a coleção dada contém menos de 2 elementos.
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, ...Repita um item.
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'As teclas de reindex do valor-chave iterável usando a função Indexer.
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,
// ],
// ]Reverta os elementos de um iterável.
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 AlicePule n elementos no itemerável após deslocamento opcional.
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'Extraia uma fatia do iterável.
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]Itera os caracteres individuais de uma string.
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']Retornar elementos do iterável, desde que o predicado seja verdadeiro.
Interrompe a iteração assim que o predicado retornar false, mesmo que outros elementos mais tarde eventualmente retornem verdadeiros (diferente do filtro).
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 Conte sequencialmente para sempre.
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 ...Passe pelos elementos de uma coleção sequencialmente para sempre.
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, ...Repita um item para sempre.
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?', ... Gerar seleções aleatórias a partir de uma matriz de valores.
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]Gere gotas de moedas aleatórias (0 ou 1).
Random::coinFlip(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: coinFlip ( $ repetitions ) as $ coinFlip ) {
print ( $ coinFlip );
}
// 1, 0, 1, 1, 0, ... [random]Gerar números aleatórios (números inteiros).
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]Gerar uma porcentagem aleatória entre 0 e 1.
Random::percentage(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: percentage ( $ repetitions ) as $ percentage ) {
print ( $ percentage );
}
// 0.30205562629132, 0.59648594775233, ... [random]Gerar mãos aleatórias de papel-rochas-tesors.
Random::rockPaperScissors(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: rockPaperScissors ( $ repetitions ) as $ rpsHand ) {
print ( $ rpsHand );
}
// 'paper', 'rock', 'rock', 'scissors', ... [random] Retorna uma distribuição de frequência dos dados.
Math::frequencies(iterable $data, bool $strict = true): Generator
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
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: 1Retorna uma distribuição de frequência relativa dos dados.
Math::relativeFrequencies(iterable $data, bool $strict = true): Generator
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
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.166Acumule a média de execução em uma lista de números.
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, 87Acumule a diferença em execução em uma lista de números.
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, -15Forneça um valor inicial opcional para liderar a diferença de execução.
use IterTools Math ;
$ dartsScores = [ 50 , 50 , 25 , 50 ];
$ startingScore = 501 ;
foreach (Math:: runningDifference ( $ dartsScores , $ startingScore ) as $ runningScore ) {
print ( $ runningScore );
}
// 501, 451, 401, 376, 326Acumule o máximo em execução em uma lista de números.
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, 5Acumule o mínimo em execução em uma lista de números.
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, 1Acumule o produto em execução em uma lista de números.
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, 120Forneça um valor inicial opcional para liderar o produto em execução.
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, 600Acumule o total em execução em uma lista de números.
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, 15Forneça um valor inicial opcional para liderar o total em execução.
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 Filtre os elementos do iterável retornando apenas elementos distintos.
Set::distinct(iterable $data, bool $strict = true)
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
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, 3Filtre os elementos do iterável, retornando apenas elementos distintos de acordo com uma função de comparador personalizada.
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.Iterado interseção de iteráveis.
Set::intersection(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras de interseção de multiset se aplicam.
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, pawnIterra a interseção de iteráveis usando a coerção do tipo.
Set::intersectionCoercive(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras de interseção de multiset se aplicam.
use IterTools Set ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 ];
foreach (Set:: intersectionCoercive ( $ numbers , $ numerics ) as $ commonNumber ) {
print ( $ commonNumber );
}
// 1, 2, 3Iterra a interseção em M-partial de iteráveis.
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, phpIterra a interseção m-parcial de iteráveis usando a coerção do tipo.
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, 3Itera a diferença simétrica dos iteráveis.
Set::symmetricDifference(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras de diferença de múltiplos porte serão aplicadas.
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, 9Itera a diferença simétrica de iteráveis com coerção de tipo.
Set::symmetricDifferenceCoercive(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras de diferença de múltiplos porte serão aplicadas.
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, 9Itera a união dos iteráveis.
Set::union(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras da união de vários eixos se aplicarão.
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, 7Itera a união de iteráveis com coerção de tipo.
Set::unionCoercive(iterable ...$iterables)
Se os iteráveis de entrada produzirem itens duplicados, as regras da união de vários eixos se aplicarão.
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 Itera a coleção classificada, mantendo as relações de índice -chave associativas.
Sort::sort(iterable $data, callable $comparator = null)
Usa a classificação padrão se a função do comparador opcional não é fornecida.
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,776Itera a coleção classificada.
Sort::sort(iterable $data, callable $comparator = null)
Usa a classificação padrão se a função do comparador opcional não é fornecida.
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 Itera as linhas de um arquivo 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 arrayItera as linhas de um arquivo.
File::readLines(resource $fileHandle)
use IterTools File ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
foreach (File:: readLines ( $ fileHandle ) as $ line ) {
print ( $ line );
}Retorne vários iteradores independentes (duplicados) de um único iterável.
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']Transforma qualquer itemerável para uma matriz.
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ iterator = new ArrayIterator ([ 1 , 2 , 3 , 4 , 5 ]);
$ array = Transform:: toArray ( $ iterator );Transforma qualquer itemerável para uma matriz associativa.
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',
// ]Transforma qualquer iterável para um iterador.
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ array = [ 1 , 2 , 3 , 4 , 5 ];
$ iterator = Transform:: toIterator ( $ array );Retorna true se todos os elementos corresponderem à função de predicado.
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 );
// falseRetorna verdadeiro se todos os elementos forem únicos.
Summary::allUnique(iterable $data, bool $strict = true): bool
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Summary:: allUnique ( $ items );
// trueRetorna true se algum elemento corresponde à função de predicado.
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 );
// trueRetorna True se todos os iteáveis forem permutações um do outro.
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 );
// trueRetorna true se todos os iteráveis forem permutações um do outro com coerção de tipo.
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 );
// trueRetorna true se exatamente n itens são verdadeiros de acordo com uma função de predicado.
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 );
// falseRetorna True se o iterável estiver vazio sem itens.
Summary::isEmpty(iterable $data): bool
use IterTools Summary ;
$ data = []
$ boolean = Summary:: isEmpty ( $ data );
// trueRetorna true se todos os elementos da coleção determinada que satisfazem o predicado aparecer antes de todos os elementos que não o fazem.
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 );Retorna True se os elementos forem classificados, caso contrário, falsa.
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 );
// falseRetorna True se os elementos forem classificados reversos, caso contrário, falsa.
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 );
// falseRetorna true se nenhum elemento corresponder à função de predicado.
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 );
// trueRetorna True se todas as coleções dadas forem iguais.
Para uma única lista iterável iterável ou vazia, retorna 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 );
// falseRetorna true se todas as coleções dadas tiverem os mesmos comprimentos.
Para uma única lista iterável iterável ou vazia, retorna 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 Reduz para a média média.
Retorna nulo se a coleção estiver vazia.
Reduce::toAverage(iterable $data): float
use IterTools Reduce ;
$ grades = [ 100 , 90 , 95 , 85 , 94 ];
$ finalGrade = Reduce:: toAverage ( $ numbers );
// 92.8Reduz iterável ao seu comprimento.
Reduce::toCount(iterable $data): int
use IterTools Reduce ;
$ someIterable = ImportantThing:: getCollectionAsIterable ();
$ length = Reduce:: toCount ( $ someIterable );
// 3Reduz iterável ao seu primeiro elemento.
Reduce::toFirst(iterable $data): mixed
Lança LengthException se a coleta estiver vazia.
use IterTools Reduce ;
$ medals = [ ' gold ' , ' silver ' , ' bronze ' ];
$ first = Reduce:: toFirst ( $ medals );
// goldReduz iterável para seus primeiros e últimos elementos.
Reduce::toFirstAndLast(iterable $data): array{mixed, mixed}
Lança LengthException se a coleta estiver vazia.
use IterTools Reduce ;
$ weekdays = [ ' Monday ' , ' Tuesday ' , ' Wednesday ' , ' Thursday ' , ' Friday ' ];
$ firstAndLast = Reduce:: toFirstAndLast ( $ weekdays );
// [Monday, Friday]Reduz iterável ao seu último elemento.
Reduce::toLast(iterable $data): mixed
Lança LengthException se a coleta estiver vazia.
use IterTools Reduce ;
$ gnomesThreePhasePlan = [ ' Collect underpants ' , ' ? ' , ' Profit ' ];
$ lastPhase = Reduce:: toLast ( $ gnomesThreePhasePlan );
// ProfitReduz ao valor máximo.
Reduce::toMax(iterable $data, callable $compareBy = null): mixed|null
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis. 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
// ];Reduz para o valor mínimo.
Reduce::toMin(iterable $data, callable $compareBy = null): mixed|null
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis. 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
// ]Reduz a matriz de seus limites superior e inferior (máx e min).
Reduce::toMinMax(iterable $numbers, callable $compareBy = null): array
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis.[null, null] se a coleção dada estiver vazia. 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
// ],
// ]Reduz a valor na enésima posição.
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 );
// 20Reduz ao produto de seus elementos.
Retorna nulo se a coleção estiver vazia.
Reduce::toProduct(iterable $data): number|null
use IterTools Reduce ;
$ primeFactors = [ 5 , 2 , 2 ];
$ number = Reduce:: toProduct ( $ primeFactors );
// 20Reduz a coleção dada a um valor aleatório dentro dela.
Reduce::toRandomValue(iterable $data): mixed
use IterTools Reduce ;
$ sfWakeupOptions = [ ' mid ' , ' low ' , ' overhead ' , ' throw ' , ' meaty ' ];
$ wakeupOption = Reduce:: toRandomValue ( $ sfWakeupOptions );
// e.g., throwReduz a coleção dada ao seu alcance (diferença entre máximo e min).
Reduce::toRange(iterable $numbers): int|float
Retorna 0 se a fonte iterável estiver vazia.
use IterTools Reduce ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Reduce:: toRange ( $ numbers );
// 20Reduz para uma string unindo todos os elementos.
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!Reduz à soma de seus elementos.
Reduce::toSum(iterable $data): number
use IterTools Reduce ;
$ parts = [ 10 , 20 , 30 ];
$ sum = Reduce:: toSum ( $ parts );
// 60Reduza os elementos para um único valor usando a função Reducer.
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 Os fluxos fornecem uma interface fluente para transformar matrizes e iteráveis através de um pipeline de operações.
Os fluxos são compostos de:
$ 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
}Cria fluxo de um iterável.
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 Cria fluxo de n gotas de moedas aleatórias.
Stream::ofCoinFlips(int $repetitions): Stream
use IterTools Stream ;
$ result = Stream:: ofCoinFlips ( 10 )
-> filterTrue ()
-> toCount ();
// 5 (random) Cria um fluxo de linhas de um arquivo 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 ();Cria fluxo de nada.
Stream::ofEmpty(): Stream
use IterTools Stream ;
$ result = Stream:: ofEmpty ()
-> chainWith ([ 1 , 2 , 3 ])
-> toArray ();
// 1, 2, 3 Cria um fluxo de linhas de um arquivo.
Stream::ofFileLines(resource $fileHandle): Stream
use IterTools Stream ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
$ result = Stream:: of ( $ fileHandle )
-> map ( ' strtoupper ' );
-> toArray ();Cria fluxo de seleções aleatórias de uma matriz de valores.
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) Cria fluxo de números aleatórios (números inteiros).
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) Cria fluxo de porcentagens aleatórias entre 0 e 1.
Stream::ofRandomPercentage(int $repetitions): Stream
use IterTools Stream ;
$ stream = Stream:: ofRandomPercentage ( 3 )
-> toArray ();
// 0.8012566976245, 0.81237281724151, 0.61676896329459 [random] Cria fluxo de uma variedade de números.
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 Cria o fluxo de mãos de papel-paper-tesors.
Stream::ofRockPaperScissors(int $repetitions): Stream
use IterTools Stream ;
$ rps = Stream:: ofRockPaperScissors ( 5 )
-> toArray ();
// 'paper', 'rock', 'rock', 'scissors', 'paper' [random]Classifica o fluxo, mantendo as teclas.
$stream->asort(callable $comparator = null)
Se o comparador não for fornecido, os elementos da fonte iterável devem ser comparáveis.
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, Retorne um fluxo encadeando fontes adicionais em um único fluxo consecutivo.
$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 Compressa para um novo fluxo filtrando dados que não estão selecionados.
$stream->compress(iterable $selectors): Stream
Seletores indicam quais dados. True Value seleciona o item. Falso Value filtra os dados.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> compress ([ 0 , 1 , 1 ])
-> toArray ();
// 2, 3 Compressa para um novo fluxo filtrando as teclas que não foram selecionadas.
$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', Retorne um fluxo que consiste em pedaços de elementos do fluxo.
$stream->chunkwise(int $chunkSize): Stream
O tamanho do pedaço deve ser pelo menos 1.
use IterTools Stream ;
$ friends = [ ' Ross ' , ' Rachel ' , ' Chandler ' , ' Monica ' , ' Joey ' ];
$ result = Stream:: of ( $ friends )
-> chunkwise ( 2 )
-> toArray ();
// ['Ross', 'Rachel'], ['Chandler', 'Monica'], ['Joey'] Retorne um fluxo que consiste em pedaços de elementos sobrepostos do fluxo.
$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] Retorne um fluxo filtrando os elementos do fluxo retornando apenas elementos distintos.
$stream->distinct(bool $strict = true): Stream
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
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 Retorne um fluxo filtrando os elementos do fluxo retornando apenas elementos distintos de acordo com uma função de comparador personalizada.
$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 Solte os elementos do fluxo enquanto a função de predicado é verdadeira.
$stream->dropWhile(callable $predicate): Stream
Depois que a função predicada retorna falsa uma vez, todos os elementos restantes são retornados.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ]
$ result = Stream:: of ( $ input )
-> dropWhile ( fn ( $ value ) => $ value < 3 )
-> toArray ();
// 3, 4, 5 Filtre os elementos do fluxo apenas mantendo os elementos em que a função predicada é verdadeira.
$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 Filtre os elementos do fluxo apenas mantendo os elementos que são verdadeiros.
$stream->filterTrue(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterTrue ()
-> toArray ();
// 1, 2, 3, 4 Filtre os elementos do fluxo apenas mantendo os elementos que são falsamente.
$stream->filterFalse(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterFalse ()
-> toArray ();
// 0, 0 Filtre os elementos do fluxo apenas mantendo os elementos em que a função de predicado nas teclas é verdadeira.
$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 Mapeie uma função nos elementos do fluxo e achate os resultados.
$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] Achate um fluxo multidimensional.
$stream->flatten(int $dimensions = 1): Stream
$ data = [ 1 , [ 2 , 3 ], [ 4 , 5 ]];
$ result = Stream:: of ( $ data )
-> flatten ( $ mapper )
-> toArray ();
// [1, 2, 3, 4, 5] Distribuição de frequência dos elementos do fluxo.
$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] Retorne um agrupamento de fluxo por um elemento de dados comum.
$stream->groupBy(callable $groupKeyFunction, callable $itemKeyFunction = null): Stream
$groupKeyFunction determina a chave para agrupar elementos por.$itemKeyFunction opcional permite índices personalizados dentro de cada membro do grupo. 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]
}Retorne um fluxo de bicicleta pelos elementos do fluxo sequencialmente para sempre.
$stream->infiniteCycle(): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> infiniteCycle ()
-> print ();
// 1, 2, 3, 1, 2, 3, ... Retorne um fluxo cruzando o fluxo com os iteráveis de entrada.
$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 Retorne um fluxo cruzando o fluxo com os iteráveis de entrada usando a coerção do tipo.
$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' Retorne um fluxo até um limite.
Paradas mesmo que mais dados disponíveis se o limite atingido.
$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) Retorne um fluxo contendo o resultado do mapeamento de uma função em cada elemento do fluxo.
$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 Retorne um fluxo que consiste em pares de elementos do fluxo.
$stream->pairwise(): Stream
Retorna o fluxo vazio se a coleção dada contém menos de 2 elementos.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ stream = Stream:: of ( $ input )
-> pairwise ()
-> toArray ();
// [1, 2], [2, 3], [3, 4], [4, 5] Retorne um fluxo interceptando parcialmente o fluxo com os iteráveis de entrada.
$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 Retorne um fluxo interceptando parcialmente o fluxo com os iteráveis de entrada usando a coerção do tipo.
$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' Retorne um novo fluxo de elementos de valor-chave reindexado pela função Indexer-chave.
$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,
// ],
// ] Distribuição de frequência relativa dos elementos do fluxo.
$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 Reverta os elementos de um fluxo.
$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 Retorne um fluxo acumulando a média de execução (média) sobre o fluxo.
$stream->runningAverage(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 3 , 5 ];
$ result = Stream:: of ( $ input )
-> runningAverage ()
-> toArray ();
// 1, 2, 3 Retorne um fluxo acumulando a diferença em execução sobre o fluxo.
$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 Retorne um fluxo acumulando o máximo em execução sobre o fluxo.
$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 Retorne um fluxo acumulando o MIN em execução sobre o fluxo.
$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 Retorne um fluxo acumulando o produto em execução sobre o fluxo.
$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 Retorne um fluxo acumulando o total em execução sobre o fluxo.
$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 Pule alguns elementos do fluxo.
$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' Extraia uma fatia do fluxo.
$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] Classifica o fluxo.
$stream->sort(callable $comparator = null)
Se o comparador não for fornecido, os elementos da fonte iterável devem ser comparáveis.
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 Retorne um fluxo da diferença simétrica do fluxo e do iterables fornecido.
$stream->symmetricDifferenceWith(iterable ...$iterables): Stream
NOTA: Se os iteráveis de entrada produzirem itens duplicados, as regras de interseção multiset se aplicam.
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 Retorne um fluxo da diferença simétrica do fluxo e dos iteráveis dados usando a coerção do tipo.
$stream->symmetricDifferenceCoerciveWith(iterable ...$iterables): Stream
NOTA: Se os iteráveis de entrada produzirem itens duplicados, as regras de interseção multiset se aplicam.
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 Mantenha os elementos do fluxo, desde que o predicado seja verdadeiro.
$stream->takeWhile(callable $predicate): Stream
Se nenhum predicado for fornecido, o valor booleano dos dados será usado.
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 Retorne um fluxo que consiste na união do fluxo e nos iteráveis de entrada.
$stream->unionWith(iterable ...$iterables): Stream
NOTA: Se os iteráveis de entrada produzirem itens duplicados, as regras da união multiset se aplicam.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionWith ([ 3 , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] Retorne um fluxo que consiste na união do fluxo e nos iteráveis de entrada usando a coerção de tipo.
$stream->unionCoerciveWith(iterable ...$iterables): Stream
NOTA: Se os iteráveis de entrada produzirem itens duplicados, as regras da união multiset se aplicam.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionCoerciveWith ([ ' 3 ' , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] Retorne um fluxo que consiste em várias coleções iteráveis transmitidas simultaneamente.
$stream->zipWith(iterable ...$iterables): Stream
Para comprimentos irregulares, as iterações para quando o mais curto iterável está esgotado.
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] Retorne um fluxo que consiste em várias coleções iteráveis, usando um valor de preenchimento padrão se não for igual.
$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, ?]
}Retorne um fluxo que consiste em várias coleções iteráveis de comprimentos iguais transmitidos simultaneamente.
$stream->zipEqualWith(iterable ...$iterables): Stream
Funciona como Stream::zipWith() Método, mas lança longException Se os comprimentos não forem iguais, ou seja, pelo menos um iterador termina diante dos outros.
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]
}Retorne um fluxo que consiste em várias coleções iteráveis transmitidas simultaneamente.
$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]
}Retorna true se todos os elementos corresponderem à função de predicado.
$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 Retorna verdadeiro se todos os elementos forem únicos.
$stream->allUnique(bool $strict = true): bool
Padrões para comparações rigorosas do tipo. Defina rigoroso como falso para comparações de coerção de tipo.
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Stream:: of ( $ items )
-> allUnique ();
// true Retorna true se algum elemento corresponde à função de predicado.
$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 Retorna true se todos os iteráveis forem permutações com o fluxo.
$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 Retorna true se todos os iteráveis forem permutações com fluxo com coerção de tipo.
$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 Retorna true se exatamente n itens são verdadeiros de acordo com uma função de predicado.
$stream->exactlyN(int $n, callable $predicate = null): bool
use IterTools Summary ;
$ twoTruthsAndALie = [ true , true , false ];
$ n = 2 ;
$ boolean = Stream:: of ( $ twoTruthsAndALie )-> exactlyN ( $ n );
// true Retorna true se o fluxo estiver vazio sem itens.
$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 Retorna true se todos os elementos da coleção determinada que satisfazem o predicado aparecer antes de todos os elementos que não o fazem.
$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 Retorna true se a fonte iterável for classificada em ordem crescente; caso contrário, falsa.
$stream->isSorted(): bool
Os itens de fonte iterável devem ser comparáveis.
Retorna true se a fonte iterável estiver vazia ou tiver apenas um elemento.
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 Retorna true se a fonte iterável for classificada em ordem decrescente reversa; caso contrário, falsa.
$stream->isReversed(): bool
Os itens de fonte iterável devem ser comparáveis.
Retorna true se a fonte iterável estiver vazia ou tiver apenas um elemento.
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 Retorna true se nenhum elemento corresponder à função de predicado.
$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 Retorna verdadeira se a fonte iterável e todas as coleções são iguais.
$stream->sameWith(iterable ...$iterables): bool
Para a lista de iteráveis vazios retorna 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 Retorna true se a fonte iterável e todas as coleções têm os mesmos comprimentos.
$stream->sameCountWith(iterable ...$iterables): bool
Para a lista de iteráveis vazios retorna 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 Reduz a fonte iterável para a média média de seus itens.
$stream->toAverage(): mixed
Retorna nulo se a fonte iterável estiver vazia.
use IterTools Stream ;
$ input = [ 2 , 4 , 6 , 8 ];
$ result = Stream:: of ( $ iterable )
-> toAverage ();
// 5 Reduz a fonte iterável ao seu comprimento.
$stream->toCount(): mixed
use IterTools Stream ;
$ input = [ 10 , 20 , 30 , 40 , 50 ];
$ result = Stream:: of ( $ iterable )
-> toCount ();
// 5 Reduz a fonte iterável ao seu primeiro elemento.
$stream->toFirst(): mixed
Lança LengthException se a fonte iterável estiver vazia.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirst ();
// 10 Reduz a fonte iterável para seus primeiros e últimos elementos.
$stream->toFirstAndLast(): array{mixed, mixed}
Lança LengthException se a fonte iterável estiver vazia.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirstAndLast ();
// [10, 30] Reduz a fonte iterável ao seu último elemento.
$stream->toLast(): mixed
Lança LengthException se a fonte iterável estiver vazia.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toLast ();
// 30 Reduz a fonte iterável ao seu valor máximo.
$stream->toMax(callable $compareBy = null): mixed
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis. use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMax ();
// 3 Reduz a fonte iterável ao seu valor mínimo.
$stream->toMin(callable $compareBy = null): mixed
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis. use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMin ();
// -3 Reduz a corrente para a matriz de seus limites superior e inferior (máx e min).
$stream->toMinMax(callable $compareBy = null): array
$compareBy deve retornar o valor comparável.$compareBy não for fornecido, os itens da coleta determinada deverão ser comparáveis.[null, null] se a coleção dada estiver vazia. use IterTools Stream ;
$ numbers = [ 1 , 2 , 7 , - 1 , - 2 , - 3 ];
[ $ min , $ max ] = Stream:: of ( $ numbers )
-> toMinMax ();
// [-3, 7] Reduz o fluxo para valorizar na enésima posição.
$stream->toNth(int $position): mixed
Retorna nulo se a fonte iterável estiver vazia.
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 Reduz o fluxo para o produto de seus itens.
$stream->toProduct(): mixed
Retorna nulo se a fonte iterável estiver vazia.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toProduct ();
// 120 Reduz o fluxo para um valor aleatório dentro dele.
$stream->toRandomValue(): mixed
use IterTools Stream ;
$ rpsHands = [ ' rock ' , ' paper ' , ' scissors ' ]
$ range = Stream:: of ( $ numbers )
-> map ( ' strtoupper ' )
-> toRandomValue ();
// e.g., rock Reduz o fluxo para o seu alcance (diferença entre max e min).
$stream->toRange(): int|float
Retorna 0 se a fonte iterável estiver vazia.
use IterTools Stream ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Stream:: of ( $ numbers )
-> toRange ();
// 20 Reduz para uma string unindo todos os elementos.
$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! Reduz a fonte iterável para a soma de seus itens.
$stream->toSum(): mixed
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toSum ();
// 15 Reduz a fonte iterável como a função Array_Reduce ().
Mas, diferentemente array_reduce() , ele funciona com todos os tipos 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 Retorna uma variedade de elementos de fluxo.
$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] Retorna um mapa de valor-chave dos elementos do fluxo.
$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, ... ] Retorne vários fluxos independentes (duplicados).
$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'] Execute uma ação por meio de um chamável em cada item no fluxo.
$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
// ... Imprime cada item no fluxo.
$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! Imprime cada item no fluxo em sua própria linha.
$stream->println(): void
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
Stream:: of ( $ words )-> printLn ();
// IterTools
// PHP
// v1.0 Escreva o conteúdo do fluxo em um arquivo 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 Escreva o conteúdo do fluxo em um arquivo.
$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>Espreite em cada elemento entre outras operações de fluxo para fazer alguma ação sem modificar o fluxo.
$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 );Veja em todo o fluxo entre outras operações do fluxo para fazer alguma ação sem modificar o fluxo.
$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 );Veja em cada elemento entre outras operações de fluxo para imprimir cada item sem modificar o fluxo.
$stream->peekPrint(string $separator = '', string $prefix = '', string $suffix = ''): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrint ()
-> foreach ( $ someComplexCallable ); Espreite em cada elemento entre outras operações de fluxo para print_r cada item sem modificar o fluxo.
$stream->peekPrintR(callable $callback): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrintR ()
-> foreach ( $ someComplexCallable ); print_r cada item no fluxo.
$stream->printR(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> printR ();
// print_r output var_dump cada item no fluxo.
$stream->varDump(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> varDump ();
// var_dump output O itterols pode ser combinado para criar novas composições iteráveis.
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 Quando houver uma opção, o padrão fará comparações rigorosas do tipo:
Quando o tipo de coerção (tipos não rígidos) está disponível e ativado por sinalizador opcional:
O ITERTOOLS PHP está em conformidade com os seguintes padrões:
O ITERTOOLS PHP é licenciado sob a licença do MIT.
IterTools functionality is not limited to PHP and Python. Other languages have similar libraries. Familiar functionality is available when working in other languages.