
Python에서 영감을 얻은 PHP에 설계되었습니다.
IterTools는 두 가지 유형의 도구를 제공하여 반복 슈퍼 스타를 만듭니다.
루프 반복 도구 예제
foreach (Multi:: zip ([ ' a ' , ' b ' ], [ 1 , 2 ]) as [ $ letter , $ number ]) {
print ( $ letter . $ number ); // a1, b2
}스트림 반복 도구 예제
$ result = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
-> distinct () // [1, 2, 3, 4, 5]
-> map ( fn ( $ x ) => $ x ** 2 ) // [1, 4, 9, 16, 25]
-> filter ( fn ( $ x ) => $ x < 10 ) // [1, 4, 9]
-> toSum (); // 14 모든 기능은 iterable 컬렉션에서 작동합니다.
array (유형)Generator (유형)Iterator (인터페이스)Traversable (인터페이스)| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
chain | 여러 반복성을 함께 체인합니다 | Multi::chain($list1, $list2) |
zip | 가장 짧은 반복자가 완료 될 때까지 여러 컬렉션을 동시에 반복하십시오 | Multi::zip($list1, $list2) |
zipEqual | 동시에 동일한 길이의 여러 수집을 동시에 반복하면 길이가 같지 않은 경우 오류 | Multi::zipEqual($list1, $list2) |
zipFilled | 길이가 같지 않은 경우 필러 값을 사용하여 여러 컬렉션을 반복하십시오. | Multi::zipFilled($default, $list1, $list2) |
zipLongest | 가장 긴 반복자가 완료 될 때까지 여러 컬렉션을 동시에 반복하십시오 | Multi::zipLongest($list1, $list2) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
chunkwise | 청크에 의해 반복 | Single::chunkwise($data, $chunkSize) |
chunkwiseOverlap | 겹친 덩어리로 반복 | Single::chunkwiseOverlap($data, $chunkSize, $overlapSize) |
compress | 선택되지 않은 요소를 필터링합니다 | Single::compress($data, $selectors) |
compressAssociative | 선택하지 않은 키로 요소를 필터링합니다 | Single::compressAssociative($data, $selectorKeys) |
dropWhile | 술어는 사실입니다 | Single::dropWhile($data, $predicate) |
filter | 술어가 사실 인 요소에 대한 필터 | Single::filterTrue($data, $predicate) |
filterTrue | 진실 요소에 대한 필터 | Single::filterTrue($data) |
filterFalse | 거짓 요소에 대한 필터 | Single::filterFalse($data) |
filterKeys | 술어가 사실 인 키를 필터링하십시오 | Single::filterKeys($data, $predicate) |
flatMap | 기능을 항목에 맵핑하고 결과를 평평하게합니다 | Single::flaMap($data, $mapper) |
flatten | 다차원 반복 가능성을 평평하게하십시오 | Single::flatten($data, [$dimensions]) |
groupBy | 공통 요소 별 그룹 데이터 | Single::groupBy($data, $groupKeyFunction, [$itemKeyFunc]) |
limit | 한도까지 반복하십시오 | Single::limit($data, $limit) |
map | 각 항목에 함수를 맵핑하십시오 | Single::map($data, $function) |
pairwise | 연속적인 겹치는 쌍을 반복합니다 | Single::pairwise($data) |
reindex | 키 값 반복의 리인덱스 키 | Single::reindex($data, $reindexer) |
repeat | 항목을 여러 번 반복하십시오 | Single::repeat($item, $repetitions) |
reverse | 반대 순서로 요소를 반복하십시오 | Single::reverse($data) |
skip | 요소를 건너 뛰고 반복하십시오 | Single::skip($data, $count, [$offset]) |
slice | 반복 가능한 한 조각을 추출하십시오 | Single::slice($data, [$start], [$count], [$step]) |
string | 문자열의 문자를 반복하십시오 | Single::string($string) |
takeWhile | 술어는 사실입니다 | Single::takeWhile($data, $predicate) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
count | 영원히 순차적으로 계산하십시오 | Infinite::count($start, $step) |
cycle | 컬렉션을 순환하십시오 | Infinite::cycle($collection) |
repeat | 영원히 항목을 반복하십시오 | Infinite::repeat($item) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
choice | 목록에서 임의의 선택 | Random::choice($list, $repetitions) |
coinFlip | 임의의 동전 뒤집기 (0 또는 1) | Random::coinFlip($repetitions) |
number | 랜덤 숫자 | Random::number($min, $max, $repetitions) |
percentage | 0과 1 사이의 무작위 백분율 | Random::percentage($repetitions) |
rockPaperScissors | 임의의 암석-가위 손잡이 손 | Random::rockPaperScissors($repetitions) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
frequencies | 데이터의 주파수 분포 | Math::frequencies($data, [$strict]) |
relativeFrequencies | 데이터의 상대 주파수 분포 | Math::relativeFrequencies($data, [$strict]) |
runningAverage | 실행 평균 축적 | Math::runningAverage($numbers, $initialValue) |
runningDifference | 런닝 차이 축적 | Math::runningDifference($numbers, $initialValue) |
runningMax | 최대 축적 실행 | Math::runningMax($numbers, $initialValue) |
runningMin | 최소 축적 실행 | Math::runningMin($numbers, $initialValue) |
runningProduct | 제품 축적 실행 | Math::runningProduct($numbers, $initialValue) |
runningTotal | 총 축적 실행 | Math::runningTotal($numbers, $initialValue) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
distinct | 별개의 항목 만 반복하십시오 | Set::distinct($data) |
distinctBy | 사용자 정의 비교기를 사용하여 별개의 항목 만 반복하십시오 | Set::distinct($data, $compareBy) |
intersection | 반복의 교차점 | Set::intersection(...$iterables) |
intersectionCoercive | 유형 강요와 교차 | Set::intersectionCoercive(...$iterables) |
partialIntersection | 반복의 부분 교차 | Set::partialIntersection($minCount, ...$iterables) |
partialIntersectionCoercive | 유형 강요와의 부분 교차 | Set::partialIntersectionCoercive($minCount, ...$iterables) |
symmetricDifference | 반복의 대칭 차이 | Set::symmetricDifference(...$iterables) |
symmetricDifferenceCoercive | 유형 강요와 대칭 차이 | Set::symmetricDifferenceCoercive(...$iterables) |
union | 반복의 결합 | Set::union(...$iterables) |
unionCoercive | 유형 강요와 연합 | Set::unionCoercive(...$iterables) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
asort | 정렬 된 컬렉션을 유지 관리 키를 반복하십시오 | Sort::asort($data, [$comparator]) |
sort | 정렬 된 컬렉션을 반복하십시오 | Sort::sort($data, [$comparator]) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
readCsv | 교차로 CSV 파일 라인 별 | File::readCsv($fileHandle) |
readLines | 파일을 한 줄씩 반복하십시오 | File::readLines($fileHandle) |
| 반복자 | 설명 | 코드 스 니펫 |
|---|---|---|
tee | 반복 중복 반복자 | Transform::tee($data, $count) |
toArray | 반복 가능한 배열로 변환하십시오 | Transform::toArray($data) |
toAssociativeArray | 반복 가능성을 연관 배열로 변환하십시오 | Transform::toAssociativeArray($data, [$keyFunc], [$valueFunc]) |
toIterator | 반복 가능한 반복자로 변환하십시오 | Transform::toIterator($data) |
| 요약 | 설명 | 코드 스 니펫 |
|---|---|---|
allMatch | 술어에 따라 모든 항목이 참이라면 사실입니다 | Summary::allMatch($data, $predicate) |
allUnique | 모든 항목이 독특하다면 사실입니다 | Summary::allUnique($data, [$strict]) |
anyMatch | 술어에 따라 항목이 참이라면 사실입니다 | Summary::anyMatch($data, $predicate) |
arePermutations | 반복이 서로의 순열 인 경우 사실 | Summary::arePermutations(...$iterables) |
arePermutationsCoercive | 반복이 유형 강요와 함께 서로의 순열 인 경우 사실 | Summary::arePermutationsCoercive(...$iterables) |
exactlyN | 정확히 n 항목이 술어에 따라 사실이라면 사실 | Summary::exactlyN($data, $n, $predicate) |
isEmpty | 반복 가능한 경우 항목이 없으면 사실입니다 | Summary::isEmpty($data) |
isPartitioned | 다른 사람 앞에서 술어에 따라 사실상 항목으로 분할 된 경우 사실 | Summary::isPartitioned($data, $predicate) |
isSorted | 반짝이는 정렬 된 경우 사실입니다 | Summary::isSorted($data) |
isReversed | 반짝이는 리버스 정렬 된 경우 | Summary::isReversed($data) |
noneMatch | 술어에 따라 항목이 없다면 사실 | Summary::noneMatch($data, $predicate) |
same | 반복이 동일하다면 사실 | Summary::same(...$iterables) |
sameCount | 반복이 길이가 같은 경우 사실입니다 | Summary::sameCount(...$iterables) |
| 감속기 | 설명 | 코드 스 니펫 |
|---|---|---|
toAverage | 평균 요소의 평균 | Reduce::toAverage($numbers) |
toCount | 반복 가능한 길이로 줄입니다 | Reduce::toCount($data) |
toFirst | 첫 번째 가치로 줄입니다 | Reduce::toFirst($data) |
toFirstAndLast | 첫 번째 및 마지막 값으로 줄입니다 | Reduce::toFirstAndLast($data) |
toLast | 마지막 가치로 줄입니다 | Reduce::toLast() |
toMax | 가장 큰 요소로 줄입니다 | Reduce::toMax($numbers, [$compareBy]) |
toMin | 가장 작은 요소로 줄입니다 | Reduce::toMin($numbers, [$compareBy]) |
toMinMax | 상부 및 하한 배열로 줄입니다 | Reduce::toMinMax($numbers, [$compareBy]) |
toNth | N 번째 위치에서 가치를 줄입니다 | Reduce::toNth($data, $position) |
toProduct | 요소의 산물을 줄입니다 | Reduce::toProduct($numbers) |
toRandomValue | 반복 가능한 값으로 무작위 값을 줄입니다 | Reduce::toRandomValue($data) |
toRange | 최대 및 최소값의 차이를 줄입니다 | Reduce::toRange($numbers) |
toString | 결합 된 문자열로 줄입니다 | Reduce::toString($data, [$separator], [$prefix], [$suffix]) |
toSum | 요소의 합으로 줄입니다 | Reduce::toSum($numbers) |
toValue | 호출 가능한 감속기를 사용하여 가치를 줄입니다 | Reduce::toValue($data, $reducer, $initialValue) |
| 원천 | 설명 | 코드 스 니펫 |
|---|---|---|
of | 반복 가능한 곳에서 스트림을 만듭니다 | Stream::of($iterable) |
ofCoinFlips | 임의의 코인 플립 스트림을 만듭니다 | Stream::ofCoinFlips($repetitions) |
ofCsvFile | CSV 파일에서 스트림을 만듭니다 | Stream::ofCsvFile($fileHandle) |
ofEmpty | 빈 스트림을 만듭니다 | Stream::ofEmpty() |
ofFileLines | 파일 줄에서 스트림을 만듭니다 | Stream::ofFileLines($fileHandle) |
ofRandomChoice | 임의의 선택 스트림을 만듭니다 | Stream::ofRandomChoice($items, $repetitions) |
ofRandomNumbers | 랜덤 숫자 스트림 생성 (정수) | Stream::ofRandomNumbers($min, $max, $repetitions) |
ofRandomPercentage | 0과 1 사이의 임의 백분율 스트림 생성 | Stream::ofRandomPercentage($repetitions) |
ofRange | 다양한 숫자의 스트림을 만듭니다 | Stream::ofRange($start, $end, $step) |
ofRockPaperScissors | 바위 가위 시체 손을 만들어냅니다 | Stream::ofRockPaperScissors($repetitions) |
| 작업 | 설명 | 코드 스 니펫 |
|---|---|---|
asort | 반복 가능한 소스 유지 관리 키를 정렬합니다 | $stream->asort([$comparator]) |
chainWith | 반복적 인 반복적 인 반복적 인 소스를 단일 반복으로 묶습니다. | $stream->chainWith(...$iterables) |
compress | 선택되지 않은 데이터를 필터링하여 소스를 압축합니다 | $stream->compress($selectors) |
compressAssociative | 선택하지 않은 키를 필터링하여 소스를 압축합니다 | $stream->compressAssociative($selectorKeys) |
chunkwise | 청크에 의해 반복 | $stream->chunkwise($chunkSize) |
chunkwiseOverlap | 겹친 덩어리로 반복 | $stream->chunkwiseOverlap($chunkSize, $overlap) |
distinct | 필터링 요소 : 고유 한 항목 만 반복하십시오 | $stream->distinct([$strict]) |
distinctBy | 필터링 요소 : 사용자 정의 비교기를 사용하여 고유 한 항목 만 반복 | $stream->distinct($compareBy) |
dropWhile | 술어 함수가 사실 인 동안 반복 가능한 소스에서 요소를 삭제합니다. | $stream->dropWhile($predicate) |
filter | 술어 함수가 참된 요소 만 필터링 | $stream->filterTrue($predicate) |
filterTrue | 진실 요소 만 필터링하십시오 | $stream->filterTrue() |
filterFalse | 거짓 요소 만 필터링하십시오 | $stream->filterFalse() |
filterKeys | 술어 기능이 참된 키를 필터링하십시오 | $stream->filterKeys($predicate) |
flatMap | 요소에 함수를 맵핑하고 결과를 평평하게합니다 | $stream->flatMap($function) |
flatten | 다차원 스트림을 평평하게하십시오 | $stream->flatten($dimensions) |
frequencies | 주파수 분포 | $stream->frequencies([$strict]) |
groupBy | 공통 데이터 요소에 의한 반복 가능한 소스 그룹 | $stream->groupBy($groupKeyFunction, [$itemKeyFunc]) |
infiniteCycle | 반복 가능한 소스의 요소를 순차적으로 순차적으로 순환하십시오 | $stream->infiniteCycle() |
intersectionWith | 반복 가능한 소스와 반복적 인 반복 | $stream->intersectionWith(...$iterables) |
intersection CoerciveWith | 반복 가능한 소스를 교차시키고 유형 강요와 반복적 인 반복 | $stream->intersectionCoerciveWith(...$iterables) |
limit | 스트림의 반복을 제한하십시오 | $stream->limit($limit) |
map | 요소에 함수를 맵핑하십시오 | $stream->map($function) |
pairwise | 반복 가능한 소스에서 요소의 쌍을 반환합니다 | $stream->pairwise() |
partialIntersectionWith | 부분적으로 반복 가능한 소스와 반복적 인 반복 | $stream->partialIntersectionWith( $minIntersectionCount, ...$iterables) |
partialIntersection CoerciveWith | 반복 가능한 소스를 부분적으로 교차시키고 유형 강요와 반복적 인 반복 | $stream->partialIntersectionCoerciveWith( $minIntersectionCount, ...$iterables) |
reindex | 키 값 스트림의 리인덱스 키 | $stream->reindex($reindexer) |
relativeFrequencies | 상대 주파수 분포 | $stream->relativeFrequencies([$strict]) |
reverse | 스트림의 역 요소 | $stream->reverse() |
runningAverage | 반복 가능한 소스에 대한 실행 평균 (평균)을 축적하십시오 | $stream->runningAverage($initialValue) |
runningDifference | 반복 가능한 소스에 대한 달리기 차이를 축적합니다 | $stream->runningDifference($initialValue) |
runningMax | 반복 가능한 소스보다 달리기 최대를 축적하십시오 | $stream->runningMax($initialValue) |
runningMin | 반복 가능한 소스 위의 실행중인 최소를 축적하십시오 | $stream->runningMin($initialValue) |
runningProduct | 반복 가능한 소스 위의 러닝 제품을 축적하십시오 | $stream->runningProduct($initialValue) |
runningTotal | 반복 가능한 소스보다 달리기 총계를 축적하십시오 | $stream->runningTotal($initialValue) |
skip | 스트림의 일부 요소를 건너 뜁니다 | $stream->skip($count, [$offset]) |
slice | 스트림 조각을 추출하십시오 | $stream->slice([$start], [$count], [$step]) |
sort | 스트림을 정렬합니다 | $stream->sort([$comparator]) |
symmetricDifferenceWith | 반짝이는 소스의 대칭 차이와 주어진 반복 | $this->symmetricDifferenceWith(...$iterables) |
symmetricDifference CoerciveWith | 반복 가능한 소스의 대칭 차이 및 유형 강요와 반복적 인 반복 | $this->symmetricDifferenceCoerciveWith( ...$iterables) |
takeWhile | 술어가 사실 인 한 반복 가능한 소스에서 요소를 반환합니다. | $stream->takeWhile($predicate) |
unionWith | 반복적 인 스트림의 연합 | $stream->unionWith(...$iterables) |
unionCoerciveWith | 유형 강요와 반복적 인 스트림의 연합 | $stream->unionCoerciveWith(...$iterables) |
zipWith | 반복적 인 소스를 동시에 반복 할 수있는 컬렉션으로 반복하십시오 | $stream->zipWith(...$iterables) |
zipEqualWith | 동시에 동일한 길이의 다른 반복 가능한 컬렉션으로 반복적 인 소스를 반복합니다. | $stream->zipEqualWith(...$iterables) |
zipFilledWith | 기본 필러를 사용하여 다른 반복 컬렉션으로 반복 소스를 반복 | $stream->zipFilledWith($default, ...$iterables) |
zipLongestWith | 반복적 인 소스를 동시에 반복 할 수있는 컬렉션으로 반복하십시오 | $stream->zipLongestWith(...$iterables) |
| 터미널 작동 | 설명 | 코드 스 니펫 |
|---|---|---|
allMatch | 스트림의 모든 항목이 술어를 일치시킬 경우 TRUE를 반환합니다 | $stream->allMatch($predicate) |
allUnique | 스트림의 모든 항목이 고유 한 경우 true를 반환합니다 | $stream->allUnique([$strict]]) |
anyMatch | 스트림의 항목이 술어와 일치하는 경우 TRUE를 반환합니다 | $stream->anyMatch($predicate) |
arePermutationsWith | 스트림의 모든 반복적 인 순열이 있으면 TRUE를 반환합니다 | $stream->arePermutationsWith(...$iterables) |
arePermutationsCoerciveWith | 유형 강요와 스트림의 모든 반복적 인 순열이 있으면 True를 반환합니다. | $stream->arePermutationsCoerciveWith(...$iterables) |
exactlyN | Predice에 따라 정확히 n 항목이 true 인 경우 true를 반환합니다. | $stream->exactlyN($n, $predicate) |
isEmpty | 스트림에 항목이없는 경우 TRUE를 반환합니다 | $stream::isEmpty() |
isPartitioned | 술어로 분할 된 경우 true를 반환합니다. | $stream::isPartitioned($predicate) |
isSorted | 스트림이 오름차순 순서로 정렬되면 true를 반환합니다 | $stream->isSorted() |
isReversed | 스트림이 리버스 내림차순 순서로 정렬되면 true를 반환합니다. | $stream->isReversed() |
noneMatch | 스트림 일치 술어에있는 항목이 없으면 진실을 반환합니다. | $stream->noneMatch($predicate) |
sameWith | 스트림과 주어진 컬렉션이 동일하면 true를 반환합니다. | $stream->sameWith(...$iterables) |
sameCountWith | 스트림과 주어진 컬렉션이 길이가 같은 경우 true를 반환합니다. | $stream->sameCountWith(...$iterables) |
| 터미널 작동 | 설명 | 코드 스 니펫 |
|---|---|---|
toAverage | 스트림을 품목의 평균 평균으로 줄입니다 | $stream->toAverage() |
toCount | 스트림을 길이로 줄입니다 | $stream->toCount() |
toFirst | 스트림을 첫 번째 값으로 줄입니다 | $stream->toFirst() |
toFirstAndLast | 스트림을 첫 번째 및 마지막 값으로 줄입니다 | $stream->toFirstAndLast() |
toLast | 스트림을 마지막 값으로 줄입니다 | $stream->toLast() |
toMax | 스트림을 최대 값으로 줄입니다 | $stream->toMax([$compareBy]) |
toMin | 스트림을 최소값으로 줄입니다 | $stream->toMin([$compareBy]) |
toMinMax | 스트림을 상부 및 하한 배열로 줄입니다 | $stream->toMinMax([$compareBy]) |
toNth | 스트림을 n 번째 위치에서 가치로 줄입니다 | $stream->toNth($position) |
toProduct | 품목의 제품으로 스트림을 줄입니다 | $stream->toProduct() |
toString | 스트림을 결합 된 문자열로 줄입니다 | $stream->toString([$separator], [$prefix], [$suffix]) |
toSum | 스트림을 해당 항목의 합으로 줄입니다 | $stream->toSum() |
toRandomValue | 스트림을 임의의 값으로 줄입니다 | $stream->toRandomValue() |
toRange | 스트림을 최대 및 최소값의 차이로 줄입니다 | $stream->toRange() |
toValue | array_reduce () 함수와 같은 스트림을 줄입니다 | $stream->toValue($reducer, $initialValue) |
| 터미널 작동 | 설명 | 코드 스 니펫 |
|---|---|---|
toArray | 스트림 요소 배열을 반환합니다 | $stream->toArray() |
toAssociativeArray | 스트림 요소의 키 값 맵을 반환합니다 | $stream->toAssociativeArray($keyFunc, $valueFunc) |
tee | 여러 동일한 스트림의 배열을 반환합니다 | $stream->tee($count) |
| 터미널 작동 | 설명 | 코드 스 니펫 |
|---|---|---|
callForEach | 각 항목에서 기능을 통해 작업을 수행하십시오 | $stream->callForEach($function) |
print | 스트림에서 각 항목을 print | $stream->print([$separator], [$prefix], [$suffix]) |
printLn | 새 라인에 각 항목을 print | $stream->printLn() |
toCsvFile | 스트림의 내용을 CSV 파일에 쓰기 | $stream->toCsvFile($fileHandle, [$headers]) |
toFile | 스트림의 내용을 파일에 씁니다 | $stream->toFile($fileHandle) |
| 디버그 작업 | 설명 | 코드 스 니펫 |
|---|---|---|
peek | 스트림 작업 사이의 각 요소를 살펴 봅니다 | $stream->peek($peekFunc) |
peekStream | 작업 사이의 전체 스트림을 살펴 봅니다 | $stream->peekStream($peekFunc) |
peekPrint | 작업간에 인쇄하여 각 요소를 살펴 봅니다 | $stream->peekPrint() |
peekPrintR | 작업 사이에 print-R을 수행하여 각 요소를 엿볼 수 있습니다 | $stream->peekPrintR() |
printR | print_r 각 항목 | $stream->printR() |
varDump | var_dump 각 항목 | $stream->varDump() |
프로젝트에서 composer.json 파일에 라이브러리를 추가하십시오.
{
"require" : {
"markrogoyski/itertools-php" : " 1.* "
}
}작곡가를 사용하여 라이브러리를 설치하십시오.
$ php composer.phar installComposer는 공급 업체 폴더 내부에 IterTools를 설치합니다. 그런 다음 .php 파일에 다음을 추가하여 자동로드와 함께 라이브러리를 사용 할 수 있습니다.
require_once __DIR__ . ' /vendor/autoload.php ' ;또는 명령 줄에서 작곡가를 사용하여 IterTools를 요구하고 설치하십시오.
$ php composer.phar require markrogoyski/itertools-php:1.*
모든 기능은 iterable 컬렉션에서 작동합니다.
array (유형)Generator (유형)Iterator (인터페이스)Traversable (인터페이스) 다중 반복성을 하나의 연속 시퀀스로 묶습니다.
Multi::chain(iterable ...$iterables)
use IterTools Multi ;
$ prequels = [ ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ];
$ originals = [ ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ];
foreach (Multi:: chain ( $ prequels , $ originals ) as $ movie ) {
print ( $ movie );
}
// 'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi'동시에 여러 개의 반복 가능한 컬렉션을 반복하십시오.
Multi::zip(iterable ...$iterables)
use IterTools Multi ;
$ languages = [ ' PHP ' , ' Python ' , ' Java ' , ' Go ' ];
$ mascots = [ ' elephant ' , ' snake ' , ' bean ' , ' gopher ' ];
foreach (Multi:: zip ( $ languages , $ mascots ) as [ $ language , $ mascot ]) {
print ( " The { $ language } language mascot is an { $ mascot } . " );
}
// The PHP language mascot is an elephant.
// ...Zip은 여러 개의 반복 가능한 입력과 함께 작동합니다.
$ names = [ ' Ryu ' , ' Ken ' , ' Chun Li ' , ' Guile ' ];
$ countries = [ ' Japan ' , ' USA ' , ' China ' , ' USA ' ];
$ signatureMoves = [ ' hadouken ' , ' shoryuken ' , ' spinning bird kick ' , ' sonic boom ' ];
foreach (Multi:: zip ( $ names , $ countries , $ signatureMoves ) as [ $ name , $ country , $ signatureMove ]) {
$ streetFighter = new StreetFighter ( $ name , $ country , $ signatureMove );
}참고 : 고르지 않은 길이의 경우 가장 짧은 반복이 소진 될 때 반복이 중지됩니다.
길이가 동시에 동일한 여러 반복 컬렉션을 반복하십시오.
길이가 같지 않은 경우 LengthException 던지기 때문에 하나 이상의 반복자가 다른 반복기보다 끝납니다.
Multi::zipEqual(iterable ...$iterables)
use IterTools Multi ;
$ letters = [ ' A ' , ' B ' , ' C ' ];
$ numbers = [ 1 , 2 , 3 ];
foreach (Multi:: zipEqual ( $ letters , $ numbers ) as [ $ letter , $ number ]) {
// ['A', 1], ['B', 2], ['C', 3]
}길이가 같지 않은 경우 기본 필러 값을 사용하여 여러 반복 가능한 컬렉션을 동시에 반복하십시오.
Multi::zipFilled(mixed $filler, iterable ...$iterables)
use IterTools Multi ;
$ default = ' ? ' ;
$ letters = [ ' A ' , ' B ' ];
$ numbers = [ 1 , 2 , 3 ];
foreach (Multi:: zipFilled ( $ default , $ letters , $ numbers ) as [ $ letter , $ number ]) {
// ['A', 1], ['B', 2], ['?', 3]
}동시에 여러 개의 반복 가능한 컬렉션을 반복하십시오.
Multi::zipLongest(iterable ...$iterables)
고르지 않은 길이의 경우, 소진 된 반복은 나머지 반복을 위해 null 생성합니다.
use IterTools Multi ;
$ letters = [ ' A ' , ' B ' , ' C ' ];
$ numbers = [ 1 , 2 ];
foreach (Multi:: zipLongest ( $ letters , $ numbers ) as [ $ letter , $ number ]) {
// ['A', 1], ['B', 2], ['C', null]
}특정 크기의 덩어리에서 요소를 반환합니다.
Single::chunkwise(iterable $data, int $chunkSize)
청크 크기는 1 이상이어야합니다.
use IterTools Single ;
$ movies = [
' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
foreach (Single:: chunkwise ( $ movies , 3 ) as $ trilogy ) {
$ trilogies [] = $ trilogy ;
}
// [
// ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith'],
// ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'],
// ['The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker]'
// ]반환 겹친 요소 덩어리.
Single::chunkwiseOverlap(iterable $data, int $chunkSize, int $overlapSize, bool $includeIncompleteTail = true)
use IterTools Single ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ];
foreach (Single:: chunkwiseOverlap ( $ numbers , 3 , 1 ) as $ chunk ) {
// [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]
}선택되지 않은 데이터를 필터링하여 반복 할 수있는 것을 압축하십시오.
Single::compress(string $data, $selectors)
use IterTools Single ;
$ movies = [
' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ goodMovies = [ 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 ];
foreach (Single:: compress ( $ movies , $ goodMovies ) as $ goodMovie ) {
print ( $ goodMovie );
}
// 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi', 'The Force Awakens'선택하지 않은 키를 필터링하여 반복 할 수있는 것을 압축하십시오.
Single::compressAssociative(string $data, array $selectorKeys)
use IterTools Single ;
$ starWarsEpisodes = [
' I ' => ' The Phantom Menace ' ,
' II ' => ' Attack of the Clones ' ,
' III ' => ' Revenge of the Sith ' ,
' IV ' => ' A New Hope ' ,
' V ' => ' The Empire Strikes Back ' ,
' VI ' => ' Return of the Jedi ' ,
' VII ' => ' The Force Awakens ' ,
' VIII ' => ' The Last Jedi ' ,
' IX ' => ' The Rise of Skywalker ' ,
];
$ originalTrilogyNumbers = [ ' IV ' , ' V ' , ' VI ' ];
foreach (Single:: compressAssociative ( $ starWarsEpisodes , $ originalTrilogyNumbers ) as $ episode => $ title ) {
print ( " $ episode : $ title " . PHP_EOL );
}
// IV: A New Hope
// V: The Empire Strikes Back
// VI: Return of the Jedi술어 함수가 사실 인 동안 반복적으로 요소를 삭제하십시오.
술어 함수가 한 번 False를 반환하면 나머지 모든 요소가 반환됩니다.
Single::dropWhile(iterable $data, callable $predicate)
use IterTools Single ;
$ scores = [ 50 , 60 , 70 , 85 , 65 , 90 ];
$ predicate = fn ( $ x ) => $ x < 70 ;
foreach (Single:: dropWhile ( $ scores , $ predicate ) as $ score ) {
print ( $ score );
}
// 70, 85, 65, 90술어 함수가 사실 인 반복 가능한 반환 요소에서만 요소를 걸러냅니다.
Single::filter(iterable $data, callable $predicate)
use IterTools Single ;
$ starWarsEpisodes = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ goodMoviePredicate = fn ( $ episode ) => $ episode > 3 && $ episode < 8 ;
foreach (Single:: filter ( $ starWarsEpisodes , $ goodMoviePredicate ) as $ goodMovie ) {
print ( $ goodMovie );
}
// 4, 5, 6, 7반복 가능한 반환 요소에서 요소를 필터링하십시오.
Single::filterTrue(iterable $data)
use IterTools Single ;
$ reportCardGrades = [ 100 , 0 , 95 , 85 , 0 , 94 , 0 ];
foreach (Single:: filterTrue ( $ reportCardGrades ) as $ goodGrade ) {
print ( $ goodGrade );
}
// 100, 95, 85, 94술어 함수가 거짓 인 반복 가능한 반환 요소에서만 요소를 걸러냅니다.
술어가 제공되지 않으면 데이터의 부울 값이 사용됩니다.
Single::filterFalse(iterable $data, callable $predicate)
use IterTools Single ;
$ alerts = [ 0 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 ];
foreach (Single:: filterFalse ( $ alerts ) as $ noAlert ) {
print ( $ noAlert );
}
// 0, 0, 0, 0메리케이트 함수가 사실 인 반복 가능한 반환 요소에서만 요소를 걸러냅니다.
Single::filterKeys(iterable $data, callable $predicate)
use IterTools Single ;
$ olympics = [
2000 => ' Sydney ' ,
2002 => ' Salt Lake City ' ,
2004 => ' Athens ' ,
2006 => ' Turin ' ,
2008 => ' Beijing ' ,
2010 => ' Vancouver ' ,
2012 => ' London ' ,
2014 => ' Sochi ' ,
2016 => ' Rio de Janeiro ' ,
2018 => ' Pyeongchang ' ,
2020 => ' Tokyo ' ,
2022 => ' Beijing ' ,
];
$ summerFilter = fn ( $ year ) => $ year % 4 === 0 ;
foreach (Single:: filterKeys ( $ olympics , $ summerFilter ) as $ year => $ hostCity ) {
print ( " $ year : $ hostCity " . PHP_EOL );
}
// 2000: Sydney
// 2004: Athens
// 2008: Beijing
// 2012: London
// 2016: Rio de Janeiro
// 2020: Tokyo함수를 반복 할 수있는 요소 만 매핑 한 다음 결과를 평평하게합니다.
Single::flatMap(iterable $data, callable $mapper)
use IterTools Single ;
$ data = [ 1 , 2 , 3 , 4 , 5 ];
$ mapper = fn ( $ item ) => [ $ item , - $ item ];
foreach (Single:: flatMap ( $ data , $ mapper ) as $ number ) {
print ( $ number . ' ' );
}
// 1 -1 2 -2 3 -3 4 -4 5 -5다차원 반복 가능을 평평하게하십시오.
Single::flatten(iterable $data, int $dimensions = 1)
use IterTools Single ;
$ multidimensional = [ 1 , [ 2 , 3 ], [ 4 , 5 ]];
$ flattened = [];
foreach (Single:: flatten ( $ multidimensional ) as $ number ) {
$ flattened [] = $ number ;
}
// [1, 2, 3, 4, 5]공통 데이터 요소 별 그룹 데이터.
Single::groupBy(iterable $data, callable $groupKeyFunction, callable $itemKeyFunction = null)
$groupKeyFunction 은 그룹 요소의 키를 결정합니다.$itemKeyFunction 각 그룹 멤버 내에서 사용자 정의 인덱스를 허용합니다. use IterTools Single ;
$ cartoonCharacters = [
[ ' Garfield ' , ' cat ' ],
[ ' Tom ' , ' cat ' ],
[ ' Felix ' , ' cat ' ],
[ ' Heathcliff ' , ' cat ' ],
[ ' Snoopy ' , ' dog ' ],
[ ' Scooby-Doo ' , ' dog ' ],
[ ' Odie ' , ' dog ' ],
[ ' Donald ' , ' duck ' ],
[ ' Daffy ' , ' duck ' ],
];
$ charactersGroupedByAnimal = [];
foreach (Single:: groupBy ( $ cartoonCharacters , fn ( $ x ) => $ x [ 1 ]) as $ animal => $ characters ) {
$ charactersGroupedByAnimal [ $ animal ] = $ characters ;
}
/*
'cat' => [
['Garfield', 'cat'],
['Tom', 'cat'],
['Felix', 'cat'],
['Heathcliff', 'cat'],
],
'dog' => [
['Snoopy', 'dog'],
['Scooby-Doo', 'dog'],
['Odie', 'dog'],
],
'duck' => [
['Donald', 'duck'],
['Daffy', 'duck'],
*/한도까지 반복하십시오.
한계에 도달하면 더 많은 데이터를 사용할 수 있더라도 중지됩니다.
Single::limit(iterable $data, int $limit)
use IterTools Single ;
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ limit = 1 ;
foreach (Single:: limit ( $ matrixMovies , $ limit ) as $ goodMovie ) {
print ( $ goodMovie );
}
// 'The Matrix' (and nothing else)함수를 각 요소에 매핑하십시오.
Single::map(iterable $data, callable $function)
use IterTools Single ;
$ grades = [ 100 , 99 , 95 , 98 , 100 ];
$ strictParentsOpinion = fn ( $ g ) => $ g === 100 ? ' A ' : ' F ' ;
foreach (Single:: map ( $ grades , $ strictParentsOpinion ) as $ actualGrade ) {
print ( $ actualGrade );
}
// A, F, F, F, A연속 겹치는 쌍을 반환합니다.
주어진 컬렉션에 2 개의 요소 미만이 포함 된 경우 빈 생성기를 반환합니다.
Single::pairwise(iterable $data)
use IterTools Single ;
$ friends = [ ' Ross ' , ' Rachel ' , ' Chandler ' , ' Monica ' , ' Joey ' , ' Phoebe ' ];
foreach (Single:: pairwise ( $ friends ) as [ $ leftFriend , $ rightFriend ]) {
print ( "{ $ leftFriend } and { $ rightFriend }" );
}
// Ross and Rachel, Rachel and Chandler, Chandler and Monica, ...항목을 반복하십시오.
Single::repeat(mixed $item, int $repetitions)
use IterTools Single ;
$ data = ' Beetlejuice ' ;
$ repetitions = 3 ;
foreach (Single:: repeat ( $ data , $ repetitions ) as $ repeated ) {
print ( $ repeated );
}
// 'Beetlejuice', 'Beetlejuice', 'Beetlejuice'인덱서 기능을 사용하여 키 값 반복의 리인덱스 키.
Single::reindex(string $data, callable $indexer)
use IterTools Single ;
$ data = [
[
' title ' => ' Star Wars: Episode IV – A New Hope ' ,
' episode ' => ' IV ' ,
' year ' => 1977 ,
],
[
' title ' => ' Star Wars: Episode V – The Empire Strikes Back ' ,
' episode ' => ' V ' ,
' year ' => 1980 ,
],
[
' title ' => ' Star Wars: Episode VI – Return of the Jedi ' ,
' episode ' => ' VI ' ,
' year ' => 1983 ,
],
];
$ reindexFunc = fn ( array $ swFilm ) => $ swFilm [ ' episode ' ];
$ reindexedData = [];
foreach (Single:: reindex ( $ data , $ reindexFunc ) as $ key => $ filmData ) {
$ reindexedData [ $ key ] = $ filmData ;
}
// [
// 'IV' => [
// 'title' => 'Star Wars: Episode IV – A New Hope',
// 'episode' => 'IV',
// 'year' => 1977,
// ],
// 'V' => [
// 'title' => 'Star Wars: Episode V – The Empire Strikes Back',
// 'episode' => 'V',
// 'year' => 1980,
// ],
// 'VI' => [
// 'title' => 'Star Wars: Episode VI – Return of the Jedi',
// 'episode' => 'VI',
// 'year' => 1983,
// ],
// ]반복 할 수있는 요소를 뒤집습니다.
Single::reverse(iterable $data)
use IterTools Single ;
$ words = [ ' Alice ' , ' answers ' , ' your ' , ' questions ' , ' Bob ' ];
foreach (Single:: reverse ( $ words ) as $ word ) {
print ( $ word . ' ' );
}
// Bob questions your answers Alice옵션 오프셋 오프셋 후 반복 할 수있는 N 요소를 건너 뜁니다.
Single::skip(iterable $data, int $count, int $offset = 0)
use IterTools Single ;
$ movies = [
' The Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' The Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ prequelsRemoved = [];
foreach (Single:: skip ( $ movies , 3 ) as $ nonPrequel ) {
$ prequelsRemoved [] = $ nonPrequel ;
} // Episodes IV - IX
$ onlyTheBest = [];
foreach (Single:: skip ( $ prequelsRemoved , 3 , 3 ) as $ nonSequel ) {
$ onlyTheBest [] = $ nonSequel ;
}
// 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi'반복 가능한 한 조각을 추출하십시오.
Single::slice(iterable $data, int $start = 0, int $count = null, int $step = 1)
use IterTools Single ;
$ olympics = [ 1992 , 1994 , 1996 , 1998 , 2000 , 2002 , 2004 , 2006 , 2008 , 2010 , 2012 , 2014 , 2016 , 2018 , 2020 , 2022 ];
$ winterOlympics = [];
foreach (Single:: slice ( $ olympics , 1 , 8 , 2 ) as $ winterYear ) {
$ winterOlympics [] = $ winterYear ;
}
// [1994, 1998, 2002, 2006, 2010, 2014, 2018, 2022]문자열의 개별 문자를 반복하십시오.
Single::string(string $string)
use IterTools Single ;
$ string = ' MickeyMouse ' ;
$ listOfCharacters = [];
foreach (Single:: string ( $ string ) as $ character ) {
$ listOfCharacters [] = $ character ;
}
// ['M', 'i', 'c', 'k', 'e', 'y', 'M', 'o', 'u', 's', 'e']술어가 사실 인 한 반복적 인 반복 요소.
다른 요소가 나중에 다른 요소가 결국 true (filtertrue와 다름)를 반환하더라도 술어가 거짓을 반환하자마자 반복을 중지합니다.
Single::takeWhile(iterable $data, callable $predicate)
use IterTools Single ;
$ prices = [ 0 , 0 , 5 , 10 , 0 , 0 , 9 ];
$ isFree = fn ( $ price ) => $ price == 0 ;
foreach (Single:: takeWhile ( $ prices , $ isFree ) as $ freePrice ) {
print ( $ freePrice );
}
// 0, 0 영원히 순차적으로 계산하십시오.
Infinite::count(int $start = 1, int $step = 1)
use IterTools Infinite ;
$ start = 1 ;
$ step = 1 ;
foreach (Infinite:: count ( $ start , $ step ) as $ i ) {
print ( $ i );
}
// 1, 2, 3, 4, 5 ...컬렉션의 요소를 순차적으로 영원히 순환하십시오.
Infinite::cycle(iterable $iterable)
use IterTools Infinite ;
$ hands = [ ' rock ' , ' paper ' , ' scissors ' ];
foreach (Infinite:: cycle ( $ hands ) as $ hand ) {
RockPaperScissors:: playHand ( $ hand );
}
// rock, paper, scissors, rock, paper, scissors, ...영원히 항목을 반복하십시오.
Infinite::repeat(mixed $item)
use IterTools Infinite ;
$ dialogue = ' Are we there yet? ' ;
foreach (Infinite:: repeat ( $ dialogue ) as $ repeated ) {
print ( $ repeated );
}
// 'Are we there yet?', 'Are we there yet?', 'Are we there yet?', ... 값 배열에서 랜덤 선택을 생성합니다.
Random::choice(array $items, int $repetitions)
use IterTools Random ;
$ cards = [ ' Ace ' , ' King ' , ' Queen ' , ' Jack ' , ' Joker ' ];
$ repetitions = 10 ;
foreach (Random:: choice ( $ cards , $ repetitions ) as $ card ) {
print ( $ card );
}
// 'King', 'Jack', 'King', 'Ace', ... [random]임의의 코인 플립 (0 또는 1)을 생성합니다.
Random::coinFlip(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: coinFlip ( $ repetitions ) as $ coinFlip ) {
print ( $ coinFlip );
}
// 1, 0, 1, 1, 0, ... [random]랜덤 숫자 (정수)를 생성합니다.
Random::number(int $min, int $max, int $repetitions)
use IterTools Random ;
$ min = 1 ;
$ max = 4 ;
$ repetitions = 10 ;
foreach (Random:: number ( $ min , $ max , $ repetitions ) as $ number ) {
print ( $ number );
}
// 3, 2, 5, 5, 1, 2, ... [random]0과 1 사이의 무작위 백분율을 생성합니다.
Random::percentage(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: percentage ( $ repetitions ) as $ percentage ) {
print ( $ percentage );
}
// 0.30205562629132, 0.59648594775233, ... [random]임의의 암석-가위 손잡이를 생성하십시오.
Random::rockPaperScissors(int $repetitions)
use IterTools Random ;
$ repetitions = 10 ;
foreach (Random:: rockPaperScissors ( $ repetitions ) as $ rpsHand ) {
print ( $ rpsHand );
}
// 'paper', 'rock', 'rock', 'scissors', ... [random] 데이터의 주파수 분포를 반환합니다.
Math::frequencies(iterable $data, bool $strict = true): Generator
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Math ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
foreach (Math:: frequencies ( $ grades ) as $ grade => $ frequency ) {
print ( " $ grade : $ frequency " . PHP_EOL );
}
// A: 2, B: 3, C: 1데이터의 상대 주파수 분포를 반환합니다.
Math::relativeFrequencies(iterable $data, bool $strict = true): Generator
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Math ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
foreach (Math:: relativeFrequencies ( $ grades ) as $ grade => $ frequency ) {
print ( " $ grade : $ frequency " . PHP_EOL );
}
// A: 0.33, B: 0.5, C: 0.166숫자 목록에 대한 평균을 누적합니다.
Math::runningAverage(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ grades = [ 100 , 80 , 80 , 90 , 85 ];
foreach (Math:: runningAverage ( $ grades ) as $ runningAverage ) {
print ( $ runningAverage );
}
// 100, 90, 86.667, 87.5, 87숫자 목록에 대한 달리기 차이를 축적합니다.
Math::runningDifference(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ credits = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningDifference ( $ credits ) as $ runningDifference ) {
print ( $ runningDifference );
}
// -1, -3, -6, -10, -15실행 차이를 제거하기 위해 선택적인 초기 값을 제공하십시오.
use IterTools Math ;
$ dartsScores = [ 50 , 50 , 25 , 50 ];
$ startingScore = 501 ;
foreach (Math:: runningDifference ( $ dartsScores , $ startingScore ) as $ runningScore ) {
print ( $ runningScore );
}
// 501, 451, 401, 376, 326숫자 목록에 대한 최대 값을 축적하십시오.
Math::runningMax(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 1 , 2 , 1 , 3 , 5 ];
foreach (Math:: runningMax ( $ numbers ) as $ runningMax ) {
print ( $ runningMax );
}
// 1, 2, 2, 3, 5숫자 목록을 통해 실행 중 최소값을 축적하십시오.
Math::runningMin(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 3 , 4 , 2 , 5 , 1 ];
foreach (Math:: runningMin ( $ numbers ) as $ runningMin ) {
print ( $ runningMin );
}
// 3, 3, 2, 2, 1숫자 목록에 실행되는 제품을 축적하십시오.
Math::runningProduct(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningProduct ( $ numbers ) as $ runningProduct ) {
print ( $ runningProduct );
}
// 1, 2, 6, 24, 120러닝 제품을 이끌어 내기 위해 선택적인 초기 값을 제공하십시오.
use IterTools Math ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ initialValue = 5 ;
foreach (Math:: runningProduct ( $ numbers , $ initialValue ) as $ runningProduct ) {
print ( $ runningProduct );
}
// 5, 5, 10, 30, 120, 600숫자 목록에 달하는 총계를 축적하십시오.
Math::runningTotal(iterable $numbers, int|float $initialValue = null)
use IterTools Math ;
$ prices = [ 1 , 2 , 3 , 4 , 5 ];
foreach (Math:: runningTotal ( $ prices ) as $ runningTotal ) {
print ( $ runningTotal );
}
// 1, 3, 6, 10, 15런닝 총계를 이끌어 내기 위해 선택적인 초기 값을 제공하십시오.
use IterTools Math ;
$ prices = [ 1 , 2 , 3 , 4 , 5 ];
$ initialValue = 5 ;
foreach (Math:: runningTotal ( $ prices , $ initialValue ) as $ runningTotal ) {
print ( $ runningTotal );
}
// 5, 6, 8, 11, 15, 20 반복 가능한 고유 한 요소 만 반환하는 요소를 필터링하십시오.
Set::distinct(iterable $data, bool $strict = true)
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Set ;
$ chessSet = [ ' rook ' , ' rook ' , ' knight ' , ' knight ' , ' bishop ' , ' bishop ' , ' king ' , ' queen ' , ' pawn ' , ' pawn ' , ... ];
foreach (Set:: distinct ( $ chessSet ) as $ chessPiece ) {
print ( $ chessPiece );
}
// rook, knight, bishop, king, queen, pawn
$ mixedTypes = [ 1 , ' 1 ' , 2 , ' 2 ' , 3 ];
foreach (Set:: distinct ( $ mixedTypes , false ) as $ datum ) {
print ( $ datum );
}
// 1, 2, 3맞춤 비교 기능에 따라 반복 가능한 반환 고유 요소 만 필터링하십시오.
Set::distinctBy(iterable $data, callable $compareBy)
use IterTools Set ;
$ streetFighterConsoleReleases = [
[ ' id ' => ' 112233 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' Dreamcast ' ],
[ ' id ' => ' 223344 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 334455 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 445566 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 556677 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 667788 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PC ' ],
];
$ compareBy = fn ( $ sfTitle ) => $ sfTitle [ ' name ' ];
$ uniqueTitles = [];
foreach (Set:: distinctBy ( $ streetFighterConsoleReleases , $ compareBy ) as $ sfTitle ) {
$ uniqueTitles [] = $ sfTitle ;
}
// Contains one SF3 3rd Strike entry and one SFVI entry.반복의 교차점을 반복합니다.
Set::intersection(iterable ...$iterables)
입력 반복이 중복 항목을 생성하는 경우 멀티 셋 교차로 규칙이 적용됩니다.
use IterTools Set ;
$ chessPieces = [ ' rook ' , ' knight ' , ' bishop ' , ' queen ' , ' king ' , ' pawn ' ];
$ shogiPieces = [ ' rook ' , ' knight ' , ' bishop ' 'king', ' pawn ' , ' lance ' , ' gold general ' , ' silver general ' ];
foreach (Set:: intersection ( $ chessPieces , $ shogiPieces ) as $ commonPiece ) {
print ( $ commonPiece );
}
// rook, knight, bishop, king, pawn유형 강요를 사용하여 반복의 교차점을 반복합니다.
Set::intersectionCoercive(iterable ...$iterables)
입력 반복이 중복 항목을 생성하는 경우 멀티 셋 교차로 규칙이 적용됩니다.
use IterTools Set ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 ];
foreach (Set:: intersectionCoercive ( $ numbers , $ numerics ) as $ commonNumber ) {
print ( $ commonNumber );
}
// 1, 2, 3반복의 M- 부분 교차점을 반복합니다.
Set::partialIntersection(int $minIntersectionCount, iterable ...$iterables)
use IterTools Set ;
$ staticallyTyped = [ ' c++ ' , ' java ' , ' c# ' , ' go ' , ' haskell ' ];
$ dynamicallyTyped = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
foreach (Set:: partialIntersection ( 2 , $ staticallyTyped , $ dynamicallyTyped , $ supportsInterfaces ) as $ language ) {
print ( $ language );
}
// c++, java, c#, go, php유형 강요를 사용하여 반복의 M- 부분 교차를 반복합니다.
Set::partialIntersectionCoercive(int $minIntersectionCount, iterable ...$iterables)
use IterTools Set ;
$ set1 = [ 1 , 2 , 3 ],
$ set2 = [ ' 2 ' , ' 3 ' , 4 , 5 ],
$ set3 = [ 1 , ' 2 ' ],
foreach (Set:: partialIntersectionCoercive ( 2 , $ set1 , $ set2 , $ set3 ) as $ partiallyCommonNumber ) {
print ( $ partiallyCommonNumber );
}
// 1, 2, 3반복의 대칭 차이를 반복합니다.
Set::symmetricDifference(iterable ...$iterables)
입력 반복이 중복 항목을 생성하면 멀티 세트 차이 규칙이 적용됩니다.
use IterTools Set ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
foreach (Set:: symmetricDifference ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
// 1, 4, 5, 6, 7, 8, 9유형 강요와 반복의 대칭 차이를 반복합니다.
Set::symmetricDifferenceCoercive(iterable ...$iterables)
입력 반복이 중복 항목을 생성하면 멀티 세트 차이 규칙이 적용됩니다.
use IterTools Set ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
foreach (Set:: symmetricDifferenceCoercive ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
// 4, 5, 6, 7, 8, 9반복의 연합을 반복합니다.
Set::union(iterable ...$iterables)
입력 반복이 중복 항목을 생성하는 경우 Multiset Union 규칙이 적용됩니다.
use IterTools Set ;
$ a = [ 1 , 2 , 3 ];
$ b = [ 3 , 4 ];
$ c = [ 1 , 2 , 3 , 6 , 7 ];
foreach (Set:: union ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
//1, 2, 3, 4, 6, 7유형 강요와 반복의 결합을 반복합니다.
Set::unionCoercive(iterable ...$iterables)
입력 반복이 중복 항목을 생성하는 경우 Multiset Union 규칙이 적용됩니다.
use IterTools Set ;
$ a = [ ' 1 ' , 2 , 3 ];
$ b = [ 3 , 4 ];
$ c = [ 1 , 2 , 3 , 6 , 7 ];
foreach (Set:: unionCoercive ( $ a , $ b , $ c ) as $ item ) {
print ( $ item );
}
//1, 2, 3, 4, 6, 7 연관 키 인덱스 관계를 유지하면서 컬렉션을 반복하십시오.
Sort::sort(iterable $data, callable $comparator = null)
선택적 비교기 기능이 제공되지 않으면 기본 정렬을 사용합니다.
use IterTools Single ;
$ worldPopulations = [
' China ' => 1_439_323_776 ,
' India ' => 1_380_004_385 ,
' Indonesia ' => 273_523_615 ,
' Pakistan ' => 220_892_340 ,
' USA ' => 331_002_651 ,
];
foreach (Sort:: sort ( $ worldPopulations ) as $ country => $ population ) {
print ( " $ country : $ population " . PHP_EOL );
}
// Pakistan: 220,892,340
// Indonesia: 273,523,615
// USA: 331,002,651
// India: 1,380,004,385
// China: 1,439,323,776컬렉션을 반복하십시오.
Sort::sort(iterable $data, callable $comparator = null)
선택적 비교기 기능이 제공되지 않으면 기본 정렬을 사용합니다.
use IterTools Single ;
$ data = [ 3 , 4 , 5 , 9 , 8 , 7 , 1 , 6 , 2 ];
foreach (Sort:: sort ( $ data ) as $ datum ) {
print ( $ datum );
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9 CSV 파일의 줄을 반복하십시오.
File::readCsv(resource $fileHandle, string $separator = ',', string $enclosure = '"', string $escape = '\')
use IterTools File ;
$ fileHandle = fopen ( ' path/to/file.csv ' , ' r ' );
foreach (File:: readCsv ( $ fileHandle ) as $ row ) {
print_r ( $ row );
}
// Each column field is an element of the array파일의 줄을 반복하십시오.
File::readLines(resource $fileHandle)
use IterTools File ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
foreach (File:: readLines ( $ fileHandle ) as $ line ) {
print ( $ line );
}단일 반복 가능한 여러 독립 (복제 된) 반복자를 반환하십시오.
Transform::tee(iterable $data, int $count): array
use IterTools Transform ;
$ daysOfWeek = [ ' Mon ' , ' Tues ' , ' Wed ' , ' Thurs ' , ' Fri ' , ' Sat ' , ' Sun ' ];
$ count = 3 ;
[ $ week1 , $ week2 , $ week3 ] = Transform:: tee ( $ data , $ count );
// Each $week contains iterator containing ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']반복 가능한 모든 것을 배열로 변환합니다.
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ iterator = new ArrayIterator ([ 1 , 2 , 3 , 4 , 5 ]);
$ array = Transform:: toArray ( $ iterator );반복 가능한 모든 것을 연관 배열로 변환합니다.
Transform::toAssociativeArray(iterable $data, callable $keyFunc = null, callable $valueFunc = null): array
use IterTools Transform ;
$ messages = [ ' message 1 ' , ' message 2 ' , ' message 3 ' ];
$ keyFunc = fn ( $ msg ) => md5 ( $ msg );
$ valueFunc = fn ( $ msg ) => strtoupper ( $ msg );
$ associativeArray = Transform:: toAssociativeArray ( $ messages , $ keyFunc , $ valueFunc );
// [
// '1db65a6a0a818fd39655b95e33ada11d' => 'MESSAGE 1',
// '83b2330607fe8f817ce6d24249dea373' => 'MESSAGE 2',
// '037805d3ad7b10c5b8425427b516b5ce' => 'MESSAGE 3',
// ]반복 가능한 모든 반복자로 변환합니다.
Transform::toArray(iterable $data): array
use IterTools Transform ;
$ array = [ 1 , 2 , 3 , 4 , 5 ];
$ iterator = Transform:: toIterator ( $ array );모든 요소가 술어 함수와 일치하는 경우 true를 반환합니다.
Summary::allMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ finalFantasyNumbers = [ 4 , 5 , 6 ];
$ isOnSuperNintendo = fn ( $ ff ) => $ ff >= 4 && $ ff <= 6 ;
$ boolean = Summary:: allMatch ( $ finalFantasyNumbers , $ isOnSuperNintendo );
// true
$ isOnPlaystation = fn ( $ ff ) => $ ff >= 7 && $ ff <= 9 ;
$ boolean = Summary:: allMatch ( $ finalFantasyNumbers , $ isOnPlaystation );
// false모든 요소가 고유 한 경우 true를 반환합니다.
Summary::allUnique(iterable $data, bool $strict = true): bool
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Summary:: allUnique ( $ items );
// true요소가 술어 함수와 일치하는 경우 true를 반환합니다.
Summary::anyMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ answers = [ ' fish ' , ' towel ' , 42 , " don't panic " ];
$ isUltimateAnswer = fn ( $ a ) => a == 42 ;
$ boolean = Summary:: anyMatch ( $ answers , $ isUltimateAnswer );
// true모든 반복이 서로 순열되면 TRUE를 반환합니다.
Summary::arePermutations(iterable ...$iterables): bool
use IterTools Summary ;
$ iter = [ ' i ' , ' t ' , ' e ' , ' r ' ];
$ rite = [ ' r ' , ' i ' , ' t ' , ' e ' ];
$ reit = [ ' r ' , ' e ' , ' i ' , ' t ' ];
$ tier = [ ' t ' , ' i ' , ' e ' , ' r ' ];
$ tire = [ ' t ' , ' i ' , ' r ' , ' e ' ];
$ trie = [ ' t ' , ' r ' , ' i ' , ' e ' ];
$ boolean = Summary:: arePermutations ( $ iter , $ rite , $ reit , $ tier , $ tire , $ trie );
// true모든 반복성이 유형 강요와 함께 서로의 순열 인 경우 true를 반환합니다.
Summary::arePermutationsCoercive(iterable ...$iterables): bool
use IterTools Summary ;
$ set1 = [ 1 , 2.0 , ' 3 ' ];
$ set2 = [ 2.0 , ' 1 ' , 3 ];
$ set3 = [ 3 , 2 , 1 ];
$ boolean = Summary:: arePermutationsCoercive ( $ set1 , $ set2 , $ set3 );
// true술어 함수에 따라 정확히 n 항목이 true 인 경우 true를 반환합니다.
Summary::exactlyN(iterable $data, int $n, callable $predicate): bool
use IterTools Summary ;
$ twoTruthsAndALie = [ true , true , false ];
$ n = 2 ;
$ boolean = Summary:: exactlyN ( $ twoTruthsAndALie , $ n );
// true
$ ages = [ 18 , 21 , 24 , 54 ];
$ n = 4 ;
$ predicate = fn ( $ age ) => $ age >= 21 ;
$ boolean = Summary:: exactlyN ( $ ages , $ n , $ predicate );
// false반복 가능한 사람이 항목이없는 경우 진실을 반환합니다.
Summary::isEmpty(iterable $data): bool
use IterTools Summary ;
$ data = []
$ boolean = Summary:: isEmpty ( $ data );
// true술어를 만족시키는 주어진 컬렉션의 모든 요소가 그렇지 않은 모든 요소 앞에 나타나는 경우 true를 반환합니다.
Summary::isPartitioned(iterable $data, callable $predicate = null): bool
use IterTools Summary ;
$ numbers = [ 0 , 2 , 4 , 1 , 3 , 5 ];
$ evensBeforeOdds = fn ( $ item ) => $ item % 2 === 0 ;
$ boolean = Summary:: isPartitioned ( $ numbers , $ evensBeforeOdds );요소가 정렬되면 true를 반환합니다. 그렇지 않으면 거짓.
Summary::isSorted(iterable $data): bool
use IterTools Summary ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 ];
$ boolean = Summary:: isSorted ( $ numbers );
// true
$ numbers = [ 3 , 2 , 3 , 4 , 5 ];
$ boolean = Summary:: isSorted ( $ numbers );
// false요소가 리버스 정렬되면 true를 반환합니다. 그렇지 않으면 False.
Summary::isReversed(iterable $data): bool
use IterTools Summary ;
$ numbers = [ 5 , 4 , 3 , 2 , 1 ];
$ boolean = Summary:: isReversed ( $ numbers );
// true
$ numbers = [ 1 , 4 , 3 , 2 , 1 ];
$ boolean = Summary:: isReversed ( $ numbers );
// false요소가 술어 함수와 일치하지 않으면 TRUE를 반환합니다.
Summary::noneMatch(iterable $data, callable $predicate): bool
use IterTools Summary ;
$ grades = [ 45 , 50 , 61 , 0 ];
$ isPassingGrade = fn ( $ grade ) => $ grade >= 70 ;
$ boolean = Summary:: noneMatch ( $ grades , $ isPassingGrade );
// true주어진 모든 컬렉션이 동일하면 TRUE를 반환합니다.
단일 반복적이거나 빈 반복 목록 목록이 true를 반환합니다.
Summary::same(iterable ...$iterables): bool
use IterTools Summary ;
$ cocaColaIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ pepsiIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ boolean = Summary:: same ( $ cocaColaIngredients , $ pepsiIngredients );
// true
$ cocaColaIngredients = [ ' carbonated water ' , ' sugar ' , ' caramel color ' , ' phosphoric acid ' ];
$ spriteIngredients = [ ' carbonated water ' , ' sugar ' , ' citric acid ' , ' lemon lime flavorings ' ];
$ boolean = Summary:: same ( $ cocaColaIngredients , $ spriteIngredients );
// false주어진 모든 컬렉션의 길이가 같은 경우 true를 반환합니다.
단일 반복적이거나 빈 반복 목록 목록이 true를 반환합니다.
Summary::sameCount(iterable ...$iterables): bool
use IterTools Summary ;
$ prequels = [ ' Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ];
$ originals = [ ' A New Hope ' , ' Empire Strikes Back ' , ' Return of the Jedi ' ];
$ sequels = [ ' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker ' ];
$ boolean = Summary:: sameCount ( $ prequels , $ originals , $ sequels );
// true
$ batmanMovies = [ ' Batman Begins ' , ' The Dark Knight ' , ' The Dark Knight Rises ' ];
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ result = Summary:: sameCount ( $ batmanMovies , $ matrixMovies );
// false 평균 평균으로 감소합니다.
수집이 비어 있으면 NULL을 반환합니다.
Reduce::toAverage(iterable $data): float
use IterTools Reduce ;
$ grades = [ 100 , 90 , 95 , 85 , 94 ];
$ finalGrade = Reduce:: toAverage ( $ numbers );
// 92.8반복 가능한 길이를 줄입니다.
Reduce::toCount(iterable $data): int
use IterTools Reduce ;
$ someIterable = ImportantThing:: getCollectionAsIterable ();
$ length = Reduce:: toCount ( $ someIterable );
// 3첫 번째 요소로 반복 할 수 있습니다.
Reduce::toFirst(iterable $data): mixed
컬렉션이 비어 있으면 LengthException 던지십시오.
use IterTools Reduce ;
$ medals = [ ' gold ' , ' silver ' , ' bronze ' ];
$ first = Reduce:: toFirst ( $ medals );
// gold반복 가능성을 첫 번째 및 마지막 요소로 줄입니다.
Reduce::toFirstAndLast(iterable $data): array{mixed, mixed}
컬렉션이 비어 있으면 LengthException 던지십시오.
use IterTools Reduce ;
$ weekdays = [ ' Monday ' , ' Tuesday ' , ' Wednesday ' , ' Thursday ' , ' Friday ' ];
$ firstAndLast = Reduce:: toFirstAndLast ( $ weekdays );
// [Monday, Friday]마지막 요소로 반복 할 수 있습니다.
Reduce::toLast(iterable $data): mixed
컬렉션이 비어 있으면 LengthException 던지십시오.
use IterTools Reduce ;
$ gnomesThreePhasePlan = [ ' Collect underpants ' , ' ? ' , ' Profit ' ];
$ lastPhase = Reduce:: toLast ( $ gnomesThreePhasePlan );
// Profit최대 값으로 감소합니다.
Reduce::toMax(iterable $data, callable $compareBy = null): mixed|null
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다. use IterTools Reduce ;
$ numbers = [ 5 , 3 , 1 , 2 , 4 ];
$ result = Reduce:: toMax ( $ numbers );
// 5
$ movieRatings = [
[
' title ' => ' Star Wars: Episode IV - A New Hope ' ,
' rating ' => 4.6
],
[
' title ' => ' Star Wars: Episode V - The Empire Strikes Back ' ,
' rating ' => 4.8
],
[
' title ' => ' Star Wars: Episode VI - Return of the Jedi ' ,
' rating ' => 4.6
],
];
$ compareBy = fn ( $ movie ) => $ movie [ ' rating ' ];
$ highestRatedMovie = Reduce:: toMax ( $ movieRatings , $ compareBy );
// [
// 'title' => 'Star Wars: Episode V - The Empire Strikes Back',
// 'rating' => 4.8
// ];최소값으로 감소합니다.
Reduce::toMin(iterable $data, callable $compareBy = null): mixed|null
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다. use IterTools Reduce ;
$ numbers = [ 5 , 3 , 1 , 2 , 4 ];
$ result = Reduce:: toMin ( $ numbers );
// 1
$ movieRatings = [
[
' title ' => ' The Matrix ' ,
' rating ' => 4.7
],
[
' title ' => ' The Matrix Reloaded ' ,
' rating ' => 4.3
],
[
' title ' => ' The Matrix Revolutions ' ,
' rating ' => 3.9
],
[
' title ' => ' The Matrix Resurrections ' ,
' rating ' => 2.5
],
];
$ compareBy = fn ( $ movie ) => $ movie [ ' rating ' ];
$ lowestRatedMovie = Reduce:: toMin ( $ movieRatings , $ compareBy );
// [
// 'title' => 'The Matrix Resurrections',
// 'rating' => 2.5
// ]상부 및 하한 (최대 및 최소)의 배열로 줄입니다.
Reduce::toMinMax(iterable $numbers, callable $compareBy = null): array
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다.[null, null] 을 반환합니다. use IterTools Reduce ;
$ numbers = [ 1 , 2 , 7 , - 1 , - 2 , - 3 ];
[ $ min , $ max ] = Reduce:: toMinMax ( $ numbers );
// [-3, 7]
$ reportCard = [
[
' subject ' => ' history ' ,
' grade ' => 90
],
[
' subject ' => ' math ' ,
' grade ' => 98
],
[
' subject ' => ' science ' ,
' grade ' => 92
],
[
' subject ' => ' english ' ,
' grade ' => 85
],
[
' subject ' => ' programming ' ,
' grade ' => 100
],
];
$ compareBy = fn ( $ class ) => $ class [ ' grade ' ];
$ bestAndWorstSubject = Reduce:: toMinMax ( $ reportCard , $ compareBy );
// [
// [
// 'subject' => 'english',
// 'grade' => 85
// ],
// [
// 'subject' => 'programming',
// 'grade' => 100
// ],
// ]N 번째 위치에서 가치를 줄입니다.
Reduce::toNth(iterable $data, int $position): mixed
use IterTools Reduce ;
$ lotrMovies = [ ' The Fellowship of the Ring ' , ' The Two Towers ' , ' The Return of the King ' ];
$ rotk = Reduce:: toNth ( $ lotrMovies , 2 );
// 20요소의 산물로 줄어 듭니다.
수집이 비어 있으면 NULL을 반환합니다.
Reduce::toProduct(iterable $data): number|null
use IterTools Reduce ;
$ primeFactors = [ 5 , 2 , 2 ];
$ number = Reduce:: toProduct ( $ primeFactors );
// 20주어진 컬렉션을 그 안에있는 임의의 값으로 줄입니다.
Reduce::toRandomValue(iterable $data): mixed
use IterTools Reduce ;
$ sfWakeupOptions = [ ' mid ' , ' low ' , ' overhead ' , ' throw ' , ' meaty ' ];
$ wakeupOption = Reduce:: toRandomValue ( $ sfWakeupOptions );
// e.g., throw주어진 수집을 범위로 줄입니다 (Max와 Min의 차이).
Reduce::toRange(iterable $numbers): int|float
반복 가능한 소스가 비어 있으면 0 반환합니다.
use IterTools Reduce ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Reduce:: toRange ( $ numbers );
// 20모든 요소를 연결하는 문자열로 줄입니다.
Reduce::toString(iterable $data, string $separator = '', string $prefix = '', string $suffix = ''): string
use IterTools Reduce ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
$ string = Reduce:: toString ( $ words );
// IterToolsPHPv1.0
$ string = Reduce:: toString ( $ words , ' - ' );
// IterTools-PHP-v1.0
$ string = Reduce:: toString ( $ words , ' - ' , ' Library: ' );
// Library: IterTools-PHP-v1.0
$ string = Reduce:: toString ( $ words , ' - ' , ' Library: ' , ' ! ' );
// Library: IterTools-PHP-v1.0!요소의 합으로 줄입니다.
Reduce::toSum(iterable $data): number
use IterTools Reduce ;
$ parts = [ 10 , 20 , 30 ];
$ sum = Reduce:: toSum ( $ parts );
// 60감속기 기능을 사용하여 요소를 단일 값으로 줄입니다.
Reduce::toValue(iterable $data, callable $reducer, mixed $initialValue): mixed
use IterTools Reduce ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ sum = fn ( $ carry , $ item ) => $ carry + $ item ;
$ result = Reduce:: toValue ( $ input , $ sum , 0 );
// 15 스트림은 작업 파이프 라인을 통해 배열 및 반복을 변환하는 유창한 인터페이스를 제공합니다.
스트림은 다음으로 구성됩니다.
$ result = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
-> distinct () // [1, 2, 3, 4, 5]
-> map ( fn ( $ x ) => $ x ** 2 ) // [1, 4, 9, 16, 25]
-> filter ( fn ( $ x ) => $ x < 10 ) // [1, 4, 9]
-> toSum (); // 14foreach 루프를 통해 반복됩니다. $ result = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
-> distinct () // [1, 2, 3, 4, 5]
-> map ( fn ( $ x ) => $ x ** 2 ) // [1, 4, 9, 16, 25]
-> filter ( fn ( $ x ) => $ x < 10 ); // [1, 4, 9]
foreach ( $ result as $ item ) {
// 1, 4, 9
}반복 가능한 곳에서 스트림을 만듭니다.
Stream::of(iterable $iterable): Stream
use IterTools Stream ;
$ iterable = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ iterable )
-> chainWith ([ 4 , 5 , 6 ], [ 7 , 8 , 9 ])
-> zipEqualWith ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ])
-> toValue ( fn ( $ carry , $ item ) => $ carry + array_sum ( $ item ));
// 90 무작위 코인 플립의 스트림을 만듭니다.
Stream::ofCoinFlips(int $repetitions): Stream
use IterTools Stream ;
$ result = Stream:: ofCoinFlips ( 10 )
-> filterTrue ()
-> toCount ();
// 5 (random) CSV 파일의 행 스트림을 만듭니다.
Stream::ofCsvFile(resource $fileHandle, string $separator = ',', string $enclosure = '"', string = $escape = '\'): Stream
use IterTools Stream ;
$ fileHandle = fopen ( ' path/to/file.csv ' , ' r ' );
$ result = Stream:: of ( $ fileHandle )
-> toArray ();아무것도없는 스트림을 만듭니다.
Stream::ofEmpty(): Stream
use IterTools Stream ;
$ result = Stream:: ofEmpty ()
-> chainWith ([ 1 , 2 , 3 ])
-> toArray ();
// 1, 2, 3 파일 줄 스트림을 만듭니다.
Stream::ofFileLines(resource $fileHandle): Stream
use IterTools Stream ;
$ fileHandle = fopen ( ' path/to/file.txt ' , ' r ' );
$ result = Stream:: of ( $ fileHandle )
-> map ( ' strtoupper ' );
-> toArray ();값 배열에서 임의의 선택 스트림을 만듭니다.
Stream::ofRandomChoice(array $items, int $repetitions): Stream
use IterTools Stream ;
$ languages = [ ' PHP ' , ' Go ' , ' Python ' ];
$ languages = Stream:: ofRandomChoice ( $ languages , 5 )
-> toArray ();
// 'Go', 'PHP', 'Python', 'PHP', 'PHP' (random) 랜덤 숫자 (정수)의 스트림을 만듭니다.
Stream::ofRandomNumbers(int $min, int $max, int $repetitions): Stream
use IterTools Stream ;
$ min = 1 ;
$ max = 3 ;
$ reps = 7 ;
$ result = Stream:: ofRandomNumbers ( $ min , $ max , $ reps )
-> toArray ();
// 1, 2, 2, 1, 3, 2, 1 (random) 0과 1 사이의 임의 백분율의 스트림을 만듭니다.
Stream::ofRandomPercentage(int $repetitions): Stream
use IterTools Stream ;
$ stream = Stream:: ofRandomPercentage ( 3 )
-> toArray ();
// 0.8012566976245, 0.81237281724151, 0.61676896329459 [random] 다양한 숫자의 스트림을 만듭니다.
Stream::ofRange(int|float $start, int|float $end, int|float $step = 1): Stream
use IterTools Stream ;
$ numbers = Stream:: ofRange ( 0 , 5 )
-> toArray ();
// 0, 1, 2, 3, 4, 5 바위 가위가 손을 뿌린 스트림을 만듭니다.
Stream::ofRockPaperScissors(int $repetitions): Stream
use IterTools Stream ;
$ rps = Stream:: ofRockPaperScissors ( 5 )
-> toArray ();
// 'paper', 'rock', 'rock', 'scissors', 'paper' [random]스트림을 정렬하고 키를 유지합니다.
$stream->asort(callable $comparator = null)
비교기가 제공되지 않으면 반복 가능한 소스의 요소를 비교할 수 있어야합니다.
use IterTools Stream ;
$ worldPopulations = [
' China ' => 1_439_323_776 ,
' India ' => 1_380_004_385 ,
' Indonesia ' => 273_523_615 ,
' USA ' => 331_002_651 ,
];
$ result = Stream:: of ( $ worldPopulations )
-> filter ( fn ( $ pop ) => $ pop > 300_000_000 )
-> asort ()
-> toAssociativeArray ();
// USA => 331_002_651,
// India => 1_380_004_385,
// China => 1_439_323_776, 추가 소스를 한 번의 연속 스트림으로 되돌리십시오.
$stream->chainWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> chainWith ([ 4 , 5 , 6 ])
-> chainWith ([ 7 , 8 , 9 ])
-> toArray ();
// 1, 2, 3, 4, 5, 6, 7, 8, 9 선택되지 않은 데이터를 필터링하여 새 스트림으로 압축하십시오.
$stream->compress(iterable $selectors): Stream
선택기는 어떤 데이터를 나타냅니다. True Value는 항목을 선택합니다. 잘못된 값은 데이터를 필터링합니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> compress ([ 0 , 1 , 1 ])
-> toArray ();
// 2, 3 선택되지 않은 키를 필터링하여 새 스트림으로 압축하십시오.
$stream->compressAssociative(array $keys): Stream
use IterTools Stream ;
$ starWarsEpisodes = [
' I ' => ' The Phantom Menace ' ,
' II ' => ' Attack of the Clones ' ,
' III ' => ' Revenge of the Sith ' ,
' IV ' => ' A New Hope ' ,
' V ' => ' The Empire Strikes Back ' ,
' VI ' => ' Return of the Jedi ' ,
' VII ' => ' The Force Awakens ' ,
' VIII ' => ' The Last Jedi ' ,
' IX ' => ' The Rise of Skywalker ' ,
];
$ sequelTrilogyNumbers = [ ' VII ' , ' VIII ' , ' IX ' ];
$ sequelTrilogy = Stream:: of ( $ starWarsEpisodes )
-> compressAssociative ( $ sequelTrilogyNumbers )
-> toAssociativeArray ();
// 'VII' => 'The Force Awakens',
// 'VIII' => 'The Last Jedi',
// 'IX' => 'The Rise of Skywalker', 스트림에서 요소 덩어리로 구성된 스트림을 반환하십시오.
$stream->chunkwise(int $chunkSize): Stream
청크 크기는 1 이상이어야합니다.
use IterTools Stream ;
$ friends = [ ' Ross ' , ' Rachel ' , ' Chandler ' , ' Monica ' , ' Joey ' ];
$ result = Stream:: of ( $ friends )
-> chunkwise ( 2 )
-> toArray ();
// ['Ross', 'Rachel'], ['Chandler', 'Monica'], ['Joey'] 스트림에서 요소의 겹치는 덩어리로 구성된 스트림을 반환하십시오.
$stream->chunkwiseOverlap(int $chunkSize, int $overlapSize, bool $includeIncompleteTail = true): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ result = Stream:: of ( $ friends )
-> chunkwiseOverlap ( 3 , 1 )
-> toArray ()
// [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9] 스트림에서 필터링 된 스트림에서 요소를 반환하여 고유 한 요소를 반환합니다.
$stream->distinct(bool $strict = true): Stream
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Stream ;
$ input = [ 1 , 2 , 1 , 2 , 3 , 3 , ' 1 ' , ' 1 ' , ' 2 ' , ' 3 ' ];
$ stream = Stream:: of ( $ input )
-> distinct ()
-> toArray ();
// 1, 2, 3, '1', '2', '3'
$ stream = Stream:: of ( $ input )
-> distinct ( false )
-> toArray ();
// 1, 2, 3 스트림 필터링을 스트림에서 필터링하는 스트림으로 반환하십시오. 사용자 정의 비교 기능에 따라 별개의 요소를 반환합니다.
$stream->distinctBy(callable $compareBy): Stream
use IterTools Stream ;
$ streetFighterConsoleReleases = [
[ ' id ' => ' 112233 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' Dreamcast ' ],
[ ' id ' => ' 223344 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 334455 ' , ' name ' => ' Street Fighter 3 3rd Strike ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 445566 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS4 ' ],
[ ' id ' => ' 556677 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PS5 ' ],
[ ' id ' => ' 667799 ' , ' name ' => ' Street Fighter VI ' , ' console ' => ' PC ' ],
];
$ stream = Stream:: of ( $ streetFighterConsoleReleases )
-> distinctBy ( fn ( $ sfTitle ) => $ sfTitle [ ' name ' ])
-> toArray ();
// Contains one SF3 3rd Strike entry and one SFVI entry 술어 함수가 사실 인 동안 스트림에서 요소를 떨어 뜨립니다.
$stream->dropWhile(callable $predicate): Stream
술어 함수가 한 번 False를 반환하면 나머지 모든 요소가 반환됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ]
$ result = Stream:: of ( $ input )
-> dropWhile ( fn ( $ value ) => $ value < 3 )
-> toArray ();
// 3, 4, 5 스트림에서 요소를 필터링하십시오.
$stream->filter(callable $predicate): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> filter ( fn ( $ value ) => $ value > 0 )
-> toArray ();
// 1, 2, 3 스트림에서 요소를 필터링하여 진실한 요소를 유지합니다.
$stream->filterTrue(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterTrue ()
-> toArray ();
// 1, 2, 3, 4 스트림에서 요소를 필터링하여 허위 요소를 유지하십시오.
$stream->filterFalse(): Stream
use IterTools Stream ;
$ input = [ 0 , 1 , 2 , 3 , 0 , 4 ];
$ result = Stream:: of ( $ input )
-> filterFalse ()
-> toArray ();
// 0, 0 스트림에서 요소를 필터링하여 키의 술어 함수가 사실 인 요소를 유지합니다.
$stream->filterKeys(callable $filter): Stream
$ olympics = [
2000 => ' Sydney ' ,
2002 => ' Salt Lake City ' ,
2004 => ' Athens ' ,
2006 => ' Turin ' ,
2008 => ' Beijing ' ,
2010 => ' Vancouver ' ,
2012 => ' London ' ,
2014 => ' Sochi ' ,
2016 => ' Rio de Janeiro ' ,
2018 => ' Pyeongchang ' ,
2020 => ' Tokyo ' ,
2022 => ' Beijing ' ,
];
$ winterFilter = fn ( $ year ) => $ year % 4 === 2 ;
$ result = Stream:: of ( $ olympics )
-> filterKeys ( $ winterFilter )
-> toAssociativeArray ();
}
// 2002 => Salt Lake City
// 2006 => Turin
// 2010 => Vancouver
// 2014 => Sochi
// 2018 => Pyeongchang
// 2022 => Beijing 함수를 스트림의 요소에 매핑하고 결과를 평평하게합니다.
$stream->flatMap(callable $mapper): Stream
$ data = [ 1 , 2 , 3 , 4 , 5 ];
$ mapper fn ( $ item ) => ( $ item % 2 === 0 ) ? [ $ item , $ item ] : $ item ;
$ result = Stream:: of ( $ data )
-> flatMap ( $ mapper )
-> toArray ();
// [1, 2, 2, 3, 4, 4, 5] 다차원 스트림을 평평하게하십시오.
$stream->flatten(int $dimensions = 1): Stream
$ data = [ 1 , [ 2 , 3 ], [ 4 , 5 ]];
$ result = Stream:: of ( $ data )
-> flatten ( $ mapper )
-> toArray ();
// [1, 2, 3, 4, 5] 스트림 요소의 주파수 분포.
$stream->frequencies(bool $strict = true): Stream
use IterTools Stream ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
$ result = Stream:: of ( $ grades )
-> frequencies ()
-> toAssociativeArray ();
// ['A' => 2, 'B' => 3, 'C' => 1] 공통 데이터 요소로 스트림 그룹을 반환합니다.
$stream->groupBy(callable $groupKeyFunction, callable $itemKeyFunction = null): Stream
$groupKeyFunction 은 그룹 요소의 키를 결정합니다.$itemKeyFunction 각 그룹 멤버 내에서 사용자 정의 인덱스를 허용합니다. use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ groups = Stream:: of ( $ input )
-> groupBy ( fn ( $ item ) => $ item > 0 ? ' positive ' : ' negative ' );
foreach ( $ groups as $ group => $ item ) {
// 'positive' => [1, 2, 3], 'negative' => [-1, -2, -3]
}스트림 순환기를 순차적으로 영원히 순차적으로 순차적으로 반환하십시오.
$stream->infiniteCycle(): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ result = Stream:: of ( $ input )
-> infiniteCycle ()
-> print ();
// 1, 2, 3, 1, 2, 3, ... 입력 반복과 스트림을 교차하는 스트림을 반환하십시오.
$stream->intersectionWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 , 4 , 5 , 6 , 7 , ' 8 ' , ' 9 ' ];
$ oddNumbers = [ 1 , 3 , 5 , 7 , 9 , 11 ];
$ stream = Stream:: of ( $ numbers )
-> intersectionWith ( $ numerics , $ oddNumbers )
-> toArray ();
// 3, 5, 7 유형 강요를 사용하여 입력 반복과 스트림과 교차하는 스트림을 반환하십시오.
$stream->intersectionCoerciveWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ languages = [ ' php ' , ' python ' , ' c++ ' , ' java ' , ' c# ' , ' javascript ' , ' typescript ' ];
$ scriptLanguages = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
$ stream = Stream:: of ( $ languages )
-> intersectionCoerciveWith ( $ scriptLanguages , $ supportsInterfaces )
-> toArray ();
// 'php', 'typescript' 한계까지 스트림을 반환하십시오.
한계에 도달하면 더 많은 데이터를 사용할 수 있더라도 중지됩니다.
$stream->limit(int $limit): Stream
Use IterTools Single ;
$ matrixMovies = [ ' The Matrix ' , ' The Matrix Reloaded ' , ' The Matrix Revolutions ' , ' The Matrix Resurrections ' ];
$ limit = 1 ;
$ goodMovies = Stream:: of ( $ matrixMovies )
-> limit ( $ limit )
-> toArray ();
// 'The Matrix' (and nothing else) 함수를 스트림의 각 요소에 매핑 한 결과를 포함하는 스트림을 반환합니다.
$stream->map(callable $function): Stream
use IterTools Stream ;
$ grades = [ 100 , 95 , 98 , 89 , 100 ];
$ result = Stream:: of ( $ grades )
-> map ( fn ( $ grade ) => $ grade === 100 ? ' A ' : ' F ' )
-> toArray ();
// A, F, F, F, A 스트림에서 요소 쌍으로 구성된 스트림을 반환합니다.
$stream->pairwise(): Stream
주어진 컬렉션에 2 개의 요소가 포함 된 경우 빈 스트림을 반환합니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ stream = Stream:: of ( $ input )
-> pairwise ()
-> toArray ();
// [1, 2], [2, 3], [3, 4], [4, 5] 스트림을 입력 반복과 부분적으로 교차하는 스트림을 반환하십시오.
$stream->partialIntersectionWith(int $minIntersectionCount, iterable ...$iterables): Stream
use IterTools Stream ;
$ numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ];
$ numerics = [ ' 1 ' , ' 2 ' , 3 , 4 , 5 , 6 , 7 , ' 8 ' , ' 9 ' ];
$ oddNumbers = [ 1 , 3 , 5 , 7 , 9 , 11 ];
$ stream = Stream:: of ( $ numbers )
-> partialIntersectionWith ( $ numerics , $ oddNumbers )
-> toArray ();
// 1, 3, 4, 5, 6, 7, 9 유형 강요를 사용하여 스트림을 입력 반복과 부분적으로 교차하는 스트림을 반환하십시오.
$stream->partialIntersectionCoerciveWith(int $minIntersectionCount, iterable ...$iterables): Stream
use IterTools Stream ;
$ languages = [ ' php ' , ' python ' , ' c++ ' , ' java ' , ' c# ' , ' javascript ' , ' typescript ' ];
$ scriptLanguages = [ ' php ' , ' python ' , ' javascript ' , ' typescript ' ];
$ supportsInterfaces = [ ' php ' , ' java ' , ' c# ' , ' typescript ' ];
$ stream = Stream:: of ( $ languages )
-> partialIntersectionCoerciveWith ( 2 , $ scriptLanguages , $ supportsInterfaces )
-> toArray ();
// 'php', 'python', 'java', 'typescript', 'c#', 'javascript' 키 인덱서 기능에 의해 다시 표시된 키 값 요소의 새 스트림을 반환하십시오.
$stream->reindex(callable $indexer): Stream
use IterTools Stream ;
$ data = [
[
' title ' => ' Star Wars: Episode IV – A New Hope ' ,
' episode ' => ' IV ' ,
' year ' => 1977 ,
],
[
' title ' => ' Star Wars: Episode V – The Empire Strikes Back ' ,
' episode ' => ' V ' ,
' year ' => 1980 ,
],
[
' title ' => ' Star Wars: Episode VI – Return of the Jedi ' ,
' episode ' => ' VI ' ,
' year ' => 1983 ,
],
];
$ reindexFunc = fn ( array $ swFilm ) => $ swFilm [ ' episode ' ];
$ reindexResult = Stream:: of ( $ data )
-> reindex ( $ reindexFunc )
-> toAssociativeArray ();
// [
// 'IV' => [
// 'title' => 'Star Wars: Episode IV – A New Hope',
// 'episode' => 'IV',
// 'year' => 1977,
// ],
// 'V' => [
// 'title' => 'Star Wars: Episode V – The Empire Strikes Back',
// 'episode' => 'V',
// 'year' => 1980,
// ],
// 'VI' => [
// 'title' => 'Star Wars: Episode VI – Return of the Jedi',
// 'episode' => 'VI',
// 'year' => 1983,
// ],
// ] 스트림 요소의 상대 주파수 분포.
$stream->relativeFrequencies(bool $strict = true): Stream
use IterTools Stream ;
$ grades = [ ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' C ' ];
$ result = Stream:: of ( $ grades )
-> relativeFrequencies ()
-> toAssociativeArray ();
// A => 0.33, B => 0.5, C => 0.166 스트림의 요소를 뒤집습니다.
$stream->reverse(): Stream
use IterTools Stream ;
$ words = [ ' are ' , ' you ' , ' as ' , ' bored ' , ' as ' , ' I ' , ' am ' ];
$ reversed = Stream:: of ( $ words )
-> reverse ()
-> toString ( ' ' );
// am I as bored as you are 스트림을 통해 달리기 평균 (평균)을 축적하는 스트림을 반환하십시오.
$stream->runningAverage(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 3 , 5 ];
$ result = Stream:: of ( $ input )
-> runningAverage ()
-> toArray ();
// 1, 2, 3 스트림을 통해 달리기 차이를 축적하는 스트림을 반환하십시오.
$stream->runningDifference(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningDifference ()
-> toArray ();
// -1, -3, -6, -10, -15 스트림을 통해 달리기 최대를 축적하는 스트림을 반환하십시오.
$stream->runningMax(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> runningMax ()
-> toArray ();
// 1, 1, 2, 2, 3, 3 스트림을 통해 달리기 최소를 축적하는 스트림을 반환하십시오.
$stream->runningMin(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> runningMin ()
-> toArray ();
// 1, -1, -1, -2, -2, -3 흐르는 제품을 스트림 위로 누적하는 스트림을 반환하십시오.
$stream->runningProduct(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningProduct ()
-> toArray ();
// 1, 2, 6, 24, 120 스트림을 통해 달리기 총계를 축적하는 스트림을 반환하십시오.
$stream->runningTotal(int|float|null $initialValue = null): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> runningTotal ()
-> toArray ();
// 1, 3, 6, 10, 15 스트림의 일부 요소를 건너 뜁니다.
$stream->skip(int $count, int $offset = 0): Stream
use IterTools Stream ;
$ movies = [
' The Phantom Menace ' , ' Attack of the Clones ' , ' Revenge of the Sith ' ,
' A New Hope ' , ' The Empire Strikes Back ' , ' Return of the Jedi ' ,
' The Force Awakens ' , ' The Last Jedi ' , ' The Rise of Skywalker '
];
$ onlyTheBest = Stream:: of ( $ movies )
-> skip ( 3 )
-> skip ( 3 , 3 )
-> toArray ();
// 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi' 스트림 조각을 추출하십시오.
$stream->slice(int $start = 0, int $count = null, int $step = 1)
use IterTools Stream ;
$ olympics = [ 1992 , 1994 , 1996 , 1998 , 2000 , 2002 , 2004 , 2006 , 2008 , 2010 , 2012 , 2014 , 2016 , 2018 , 2020 , 2022 ];
$ summerOlympics = Stream:: of ( $ olympics )
-> slice ( 0 , 8 , 2 )
-> toArray ();
// [1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020] 스트림을 정렬합니다.
$stream->sort(callable $comparator = null)
비교기가 제공되지 않으면 반복 가능한 소스의 요소를 비교할 수 있어야합니다.
use IterTools Stream ;
$ input = [ 3 , 4 , 5 , 9 , 8 , 7 , 1 , 6 , 2 ];
$ result = Stream:: of ( $ input )
-> sort ()
-> toArray ();
// 1, 2, 3, 4, 5, 6, 7, 8, 9 스트림과 주어진 반복성의 대칭 차이의 스트림을 반환하십시오.
$stream->symmetricDifferenceWith(iterable ...$iterables): Stream
참고 : 입력 반복이 중복 항목을 생성하는 경우 멀티 셋 교차로 규칙이 적용됩니다.
use IterTools Stream ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
$ stream = Stream:: of ( $ a )
-> symmetricDifferenceWith ( $ b , $ c )
-> toArray ();
// '1', 4, 5, 6, 7, 8, 9 유형 강요를 사용하여 스트림과 주어진 반복성의 대칭 차이의 스트림을 반환하십시오.
$stream->symmetricDifferenceCoerciveWith(iterable ...$iterables): Stream
참고 : 입력 반복이 중복 항목을 생성하는 경우 멀티 셋 교차로 규칙이 적용됩니다.
use IterTools Stream ;
$ a = [ 1 , 2 , 3 , 4 , 7 ];
$ b = [ ' 1 ' , 2 , 3 , 5 , 8 ];
$ c = [ 1 , 2 , 3 , 6 , 9 ];
$ stream = Stream:: of ( $ a )
-> symmetricDifferenceCoerciveWith ( $ b , $ c )
-> toArray ();
// 4, 5, 6, 7, 8, 9 술어가 사실 인 한 요소를 스트림에서 유지하십시오.
$stream->takeWhile(callable $predicate): Stream
술어가 제공되지 않으면 데이터의 부울 값이 사용됩니다.
use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ input )
-> takeWhile ( fn ( $ value ) => abs ( $ value ) < 3 )
-> toArray ();
// 1, -1, 2, -2 스트림의 결합과 입력 반복으로 구성된 스트림을 반환하십시오.
$stream->unionWith(iterable ...$iterables): Stream
참고 : 입력 반복이 중복 항목을 생성하는 경우 Multiset Union 규칙이 적용됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionWith ([ 3 , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] 유형 강요를 사용하여 스트림의 결합과 입력 반복으로 구성된 스트림을 반환하십시오.
$stream->unionCoerciveWith(iterable ...$iterables): Stream
참고 : 입력 반복이 중복 항목을 생성하는 경우 Multiset Union 규칙이 적용됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> unionCoerciveWith ([ ' 3 ' , 4 , 5 , 6 ])
-> toArray ();
// [1, 2, 3, 4, 5, 6] 동시에 스트리밍 된 여러 반복 컬렉션으로 구성된 스트림을 반환하십시오.
$stream->zipWith(iterable ...$iterables): Stream
고르지 않은 길이의 경우 가장 짧은 반복이 소진 될 때 반복이 중지됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipWith ([ 4 , 5 , 6 ])
-> zipWith ([ 7 , 8 , 9 ])
-> toArray ();
// [1, 4, 7], [2, 5, 8], [3, 6, 9] 길이가 같지 않은 경우 기본 필러 값을 사용하여 여러 반복 가능한 컬렉션으로 구성된 스트림을 반환하십시오.
$stream->zipFilledWith(mixed $default, iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipFilledWith ( ' ? ' , [ ' A ' , ' B ' ]);
foreach ( $ stream as $ zipped ) {
// [1, A], [2, B], [3, ?]
}동시에 스트리밍 된 동일한 길이의 반복 가능한 컬렉션으로 구성된 스트림을 반환하십시오.
$stream->zipEqualWith(iterable ...$iterables): Stream
Stream::zipWith() 메소드와 같이 작동하지만 길이가 같지 않으면 longthexception을 던지고, 즉 적어도 하나의 반복기가 다른 반복기보다 먼저 끝납니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 ];
$ stream = Stream:: of ( $ input )
-> zipEqualWith ([ 4 , 5 , 6 ])
-> zipEqualWith ([ 7 , 8 , 9 ]);
foreach ( $ stream as $ zipped ) {
// [1, 4, 7], [2, 5, 8], [3, 6, 9]
}동시에 스트리밍 된 여러 반복 컬렉션으로 구성된 스트림을 반환하십시오.
$stream->zipLongestWith(iterable ...$iterables): Stream
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ stream = Stream:: of ( $ input )
-> zipLongestWith ([ 4 , 5 , 6 ])
-> zipLongestWith ([ 7 , 8 , 9 , 10 ]);
foreach ( $ stream as $ zipped ) {
// [1, 4, 7], [2, 5, 8], [3, 6, 9], [4, null, 10], [null, null, 5]
}모든 요소가 술어 함수와 일치하는 경우 true를 반환합니다.
$stream->allMatch(callable $predicate): bool
use IterTools Summary ;
$ finalFantasyNumbers = [ 4 , 5 , 6 ];
$ isOnSuperNintendo = fn ( $ ff ) => $ ff >= 4 && $ ff <= 6 ;
$ boolean = Stream:: of ( $ finalFantasyNumbers )
-> allMatch ( $ isOnSuperNintendo );
// true 모든 요소가 고유 한 경우 true를 반환합니다.
$stream->allUnique(bool $strict = true): bool
기본값은 엄격한 유형 비교로입니다. 유형 강요 비교를 위해 False로 엄격하게 설정하십시오.
use IterTools Summary ;
$ items = [ ' fingerprints ' , ' snowflakes ' , ' eyes ' , ' DNA ' ]
$ boolean = Stream:: of ( $ items )
-> allUnique ();
// true 요소가 술어 함수와 일치하는 경우 true를 반환합니다.
$stream->anyMatch(callable $predicate): bool
use IterTools Summary ;
$ answers = [ ' fish ' , ' towel ' , 42 , " don't panic " ];
$ isUltimateAnswer = fn ( $ a ) => a == 42 ;
$ boolean = Stream:: of ( $ answers )
-> anyMatch ( $ answers , $ isUltimateAnswer );
// true 모든 반복성이 스트림과의 순열 인 경우 true를 반환합니다.
$stream->arePermutationsWith(...$iterables): bool
use IterTools Summary ;
$ rite = [ ' r ' , ' i ' , ' t ' , ' e ' ];
$ reit = [ ' r ' , ' e ' , ' i ' , ' t ' ];
$ tier = [ ' t ' , ' i ' , ' e ' , ' r ' ];
$ tire = [ ' t ' , ' i ' , ' r ' , ' e ' ];
$ trie = [ ' t ' , ' r ' , ' i ' , ' e ' ];
$ boolean = Stream:: of ([ ' i ' , ' t ' , ' e ' , ' r ' ])
-> arePermutationsWith ( $ rite , $ reit , $ tier , $ tire , $ trie );
// true 모든 반복성이 유형 강요와 스트림으로 순열되는 경우 true를 반환합니다.
$stream->arePermutationsCoerciveWith(...$iterables): bool
use IterTools Summary ;
$ set2 = [ 2.0 , ' 1 ' , 3 ];
$ set3 = [ 3 , 2 , 1 ];
$ boolean = Stream:: of ([ 1 , 2.0 , ' 3 ' ])
-> arePermutationsCoerciveWith ( $ set2 , $ set3 );
// true 술어 함수에 따라 정확히 n 항목이 true 인 경우 true를 반환합니다.
$stream->exactlyN(int $n, callable $predicate = null): bool
use IterTools Summary ;
$ twoTruthsAndALie = [ true , true , false ];
$ n = 2 ;
$ boolean = Stream:: of ( $ twoTruthsAndALie )-> exactlyN ( $ n );
// true 스트림에 항목이없는 경우 TRUE를 반환합니다.
$stream->isEmpty(): bool
use IterTools Summary ;
$ numbers = [ 0 , 1 , 2 , 3 , 4 , 5 ];
$ filterFunc = fn ( $ x ) => $ x > 10 ;
$ boolean = Stream::( $ numbers )
-> filter ( $ filterFunc )
-> isEmpty ();
// true 술어를 만족시키는 주어진 컬렉션의 모든 요소가 그렇지 않은 모든 요소 앞에 나타나는 경우 true를 반환합니다.
$stream->isPartitioned(callable $predicate = null): bool
use IterTools Summary ;
$ numbers = [ 0 , 2 , 4 , 1 , 3 , 5 ];
$ evensBeforeOdds = fn ( $ item ) => $ item % 2 === 0 ;
$ boolean = Stream::( $ numbers )
-> isPartitioned ( $ evensBeforeOdds );
// true 반짝이는 소스가 오름차순 순서로 정렬되면 true를 반환합니다. 그렇지 않으면 거짓입니다.
$stream->isSorted(): bool
반복 가능한 소스의 항목은 비슷해야합니다.
반짝이는 소스가 비어 있거나 요소가 하나만 있으면 true를 반환합니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> isSorted ();
// true
$ input = [ 1 , 2 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isSorted ();
// false 반짝이는 소스가 역 하강 순서로 정렬되면 true를 반환합니다. 그렇지 않으면 거짓입니다.
$stream->isReversed(): bool
반복 가능한 소스의 항목은 비슷해야합니다.
반짝이는 소스가 비어 있거나 요소가 하나만 있으면 true를 반환합니다.
use IterTools Stream ;
$ input = [ 5 , 4 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isReversed ();
// true
$ input = [ 1 , 2 , 3 , 2 , 1 ];
$ result = Stream:: of ( $ input )
-> isReversed ();
// false 요소가 술어 함수와 일치하지 않으면 TRUE를 반환합니다.
$stream->noneMatch(callable $predicate): bool
use IterTools Summary ;
$ grades = [ 45 , 50 , 61 , 0 ];
$ isPassingGrade = fn ( $ grade ) => $ grade >= 70 ;
$ boolean = Stream:: of ( $ grades )-> noneMatch ( $ isPassingGrade );
// true 반짝이는 소스와 주어진 컬렉션이 동일하다면 True를 반환합니다.
$stream->sameWith(iterable ...$iterables): bool
빈 반복 목록의 경우 TRUE가 반환됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> sameWith ([ 1 , 2 , 3 , 4 , 5 ]);
// true
$ result = Stream:: of ( $ input )
-> sameWith ([ 5 , 4 , 3 , 2 , 1 ]);
// false 반짝이는 소스와 주어진 컬렉션의 길이가 같은 경우 true를 반환합니다.
$stream->sameCountWith(iterable ...$iterables): bool
빈 반복 목록의 경우 TRUE가 반환됩니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ input )
-> sameCountWith ([ 5 , 4 , 3 , 2 , 1 ]);
// true
$ result = Stream:: of ( $ input )
-> sameCountWith ([ 1 , 2 , 3 ]);
// false 반복 가능한 소스를 품목의 평균 평균으로 줄입니다.
$stream->toAverage(): mixed
반짝이는 소스가 비어 있으면 null을 반환합니다.
use IterTools Stream ;
$ input = [ 2 , 4 , 6 , 8 ];
$ result = Stream:: of ( $ iterable )
-> toAverage ();
// 5 반복 가능한 소스를 길이로 줄입니다.
$stream->toCount(): mixed
use IterTools Stream ;
$ input = [ 10 , 20 , 30 , 40 , 50 ];
$ result = Stream:: of ( $ iterable )
-> toCount ();
// 5 반복 가능한 소스를 첫 번째 요소로 줄입니다.
$stream->toFirst(): mixed
반짝이는 소스가 비어 있으면 LengthException 던지십시오.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirst ();
// 10 반복 가능한 소스를 첫 번째 및 마지막 요소로 줄입니다.
$stream->toFirstAndLast(): array{mixed, mixed}
반짝이는 소스가 비어 있으면 LengthException 던지십시오.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toFirstAndLast ();
// [10, 30] 반복 가능한 소스를 마지막 요소로 줄입니다.
$stream->toLast(): mixed
반짝이는 소스가 비어 있으면 LengthException 던지십시오.
use IterTools Stream ;
$ input = [ 10 , 20 , 30 ];
$ result = Stream:: of ( $ input )
-> toLast ();
// 30 반복 가능한 소스를 최대 값으로 줄입니다.
$stream->toMax(callable $compareBy = null): mixed
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다. use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMax ();
// 3 반복 가능한 소스를 최소값으로 줄입니다.
$stream->toMin(callable $compareBy = null): mixed
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다. use IterTools Stream ;
$ input = [ 1 , - 1 , 2 , - 2 , 3 , - 3 ];
$ result = Stream:: of ( $ iterable )
-> toMin ();
// -3 스트림을 상부 및 하한 (최대 및 최소)으로 줄입니다.
$stream->toMinMax(callable $compareBy = null): array
$compareBy 비슷한 값을 반환해야합니다.$compareBy 제공되지 않으면 주어진 컬렉션의 항목을 비교해야합니다.[null, null] 을 반환합니다. use IterTools Stream ;
$ numbers = [ 1 , 2 , 7 , - 1 , - 2 , - 3 ];
[ $ min , $ max ] = Stream:: of ( $ numbers )
-> toMinMax ();
// [-3, 7] 스트림을 n 번째 위치에서 가치로 줄입니다.
$stream->toNth(int $position): mixed
반짝이는 소스가 비어 있으면 null을 반환합니다.
use IterTools Stream ;
$ lotrMovies = [ ' The Fellowship of the Ring ' , ' The Two Towers ' , ' The Return of the King ' ];
$ result = Stream:: of ( $ lotrMovies )
-> toNth ( 2 );
// The Return of the King 품목의 제품으로 스트림을 줄입니다.
$stream->toProduct(): mixed
반짝이는 소스가 비어 있으면 null을 반환합니다.
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toProduct ();
// 120 스트림을 임의의 값으로 줄입니다.
$stream->toRandomValue(): mixed
use IterTools Stream ;
$ rpsHands = [ ' rock ' , ' paper ' , ' scissors ' ]
$ range = Stream:: of ( $ numbers )
-> map ( ' strtoupper ' )
-> toRandomValue ();
// e.g., rock 스트림을 범위로 줄입니다 (Max와 Min의 차이).
$stream->toRange(): int|float
반복 가능한 소스가 비어 있으면 0 반환합니다.
use IterTools Stream ;
$ grades = [ 100 , 90 , 80 , 85 , 95 ];
$ range = Stream:: of ( $ numbers )
-> toRange ();
// 20 모든 요소를 연결하는 문자열로 줄입니다.
$stream->toString(string $separator = '', string $prefix = '', string $suffix = ''): string
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
$ string = Stream:: of ( $ words )-> toString ( $ words );
// IterToolsPHPv1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' );
// IterTools-PHP-v1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' , ' Library: ' );
// Library: IterTools-PHP-v1.0
$ string = Stream:: of ( $ words )-> toString ( $ words , ' - ' , ' Library: ' , ' ! ' );
// Library: IterTools-PHP-v1.0! 반복 가능한 소스를 항목의 합으로 줄입니다.
$stream->toSum(): mixed
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toSum ();
// 15 array_reduce () 함수와 같은 반복 가능한 소스를 줄입니다.
그러나 array_reduce() 와 달리 모든 iterable 유형과 함께 작동합니다.
$stream->toValue(callable $reducer, mixed $initialValue): mixed
use IterTools Stream ;
$ input = [ 1 , 2 , 3 , 4 , 5 ];
$ result = Stream:: of ( $ iterable )
-> toValue ( fn ( $ carry , $ item ) => $ carry + $ item );
// 15 스트림 요소의 배열을 반환합니다.
$stream->toArray(): array
use IterTools Stream ;
$ array = Stream:: of ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 ])
-> distinct ()
-> map ( fn ( $ x ) => $ x ** 2 )
-> toArray ();
// [1, 4, 9, 16, 25] 스트림 요소의 키 가치 맵을 반환합니다.
$stream->toAssociativeArray(callable $keyFunc, callable $valueFunc): array
use IterTools Stream ;
$ keyFunc
$ array = Stream:: of ([ ' message 1 ' , ' message 2 ' , ' message 3 ' ])
-> map ( ' strtoupper ' )
-> toAssociativeArray (
fn ( $ s ) => md5 ( $ s ),
fn ( $ s ) => $ s
);
// [3b3f2272b3b904d342b2d0df2bf31ed4 => MESSAGE 1, 43638d919cfb8ea31979880f1a2bb146 => MESSAGE 2, ... ] 여러 독립 (복제 된) 스트림을 반환합니다.
$stream->tee(int $count): array
use IterTools Transform ;
$ daysOfWeek = [ ' Mon ' , ' Tues ' , ' Wed ' , ' Thurs ' , ' Fri ' , ' Sat ' , ' Sun ' ];
$ count = 3 ;
[ $ week1Stream , $ week2Stream , $ week3Stream ] = Stream:: of ( $ daysOfWeek )
-> tee ( $ count );
// Each $weekStream contains ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'] 스트림의 각 항목에서 호출 가능을 통해 작업을 수행하십시오.
$stream->callForEach(callable $function): void
use IterTools Stream ;
$ languages = [ ' PHP ' , ' Python ' , ' Java ' , ' Go ' ];
$ mascots = [ ' elephant ' , ' snake ' , ' bean ' , ' gopher ' ];
$ zipPrinter = fn ( $ zipped ) => print ( "{ $ zipped [ 0 ]} 's mascot: { $ zipped [ 1 ]}" );
Stream:: of ( $ languages )
-> zipWith ( $ mascots )
-> callForEach ( $ zipPrinter );
// PHP's mascot: elephant
// Python's mascot: snake
// ... 스트림에서 각 항목을 인쇄합니다.
$stream->print(string $separator = '', string $prefix = '', string $suffix = ''): void
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
Stream:: of ( $ words )-> print (); // IterToolsPHPv1.0
Stream:: of ( $ words )-> print ( ' - ' ); // IterTools-PHP-v1.0
Stream:: of ( $ words )-> print ( ' - ' , ' Library: ' ); // Library: IterTools-PHP-v1.0
Stream:: of ( $ words )-> print ( ' - ' , ' Library: ' , ' ! ' ); // Library: IterTools-PHP-v1.0! 스트림의 각 항목을 자체 라인으로 인쇄합니다.
$stream->println(): void
use IterTools Stream ;
$ words = [ ' IterTools ' , ' PHP ' , ' v1.0 ' ];
Stream:: of ( $ words )-> printLn ();
// IterTools
// PHP
// v1.0 스트림의 내용을 CSV 파일에 쓰십시오.
$stream->toCsvFile(resource $fileHandle, array $header = null, string 'separator = ',', string $enclosure = '"', string $escape = '\'): void
use IterTools Stream ;
$ starWarsMovies = [
[ ' Star Wars: Episode IV – A New Hope ' , ' IV ' , 1977 ],
[ ' Star Wars: Episode V – The Empire Strikes Back ' , ' V ' , 1980 ],
[ ' Star Wars: Episode VI – Return of the Jedi ' , ' VI ' , 1983 ],
];
$ header = [ ' title ' , ' episode ' , ' year ' ];
Stream:: of ( $ data )
-> toCsvFile ( $ fh , $ header );
// title,episode,year
// "Star Wars: Episode IV – A New Hope",IV,1977
// "Star Wars: Episode V – The Empire Strikes Back",V,1980
// "Star Wars: Episode VI – Return of the Jedi",VI,1983 스트림의 내용을 파일에 씁니다.
$stream->toFile(resource $fileHandle, string $newLineSeparator = PHP_EOL, string $header = null, string $footer = null): void
use IterTools Stream ;
$ data = [ ' item1 ' , ' item2 ' , ' item3 ' ];
$ header = ' <ul> ' ;
$ footer = ' </ul> ' ;
Stream:: of ( $ data )
-> map ( fn ( $ item ) => " <li> $ item </li> " )
-> toFile ( $ fh , PHP_EOL , $ header , $ footer );
// <ul>
// <li>item1</li>
// <li>item2</li>
// <li>item3</li>
// </ul>스트림을 수정하지 않고 약간의 작업을 수행하기 위해 다른 스트림 작업 사이의 각 요소를 살펴 봅니다.
$stream->peek(callable $callback): Stream
use IterTools Stream ;
$ logger = new SimpleLog Logger ( ' /tmp/log.txt ' , ' iterTools ' );
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peek ( fn ( $ x ) => $ logger -> info ( $ x ))
-> foreach ( $ someComplexCallable );스트림을 수정하지 않고 약간의 작업을 수행하기 위해 다른 스트림 작업 사이의 전체 스트림을 살펴 봅니다.
$stream->peekStream(callable $callback): Stream
use IterTools Stream ;
$ logger = new SimpleLog Logger ( ' /tmp/log.txt ' , ' iterTools ' );
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekStream ( fn ( $ stream ) => $ logger -> info ( $ stream ))
-> foreach ( $ someComplexCallable );스트림을 수정하지 않고 각 항목을 인쇄하기 위해 다른 스트림 작업 사이의 각 요소를 살펴 봅니다.
$stream->peekPrint(string $separator = '', string $prefix = '', string $suffix = ''): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrint ()
-> foreach ( $ someComplexCallable ); 스트림을 수정하지 않고 각 항목에 대한 다른 스트림 작업 사이의 각 요소를 print_r 봅니다.
$stream->peekPrintR(callable $callback): void
use IterTools Stream ;
Stream:: of ([ ' some ' , ' items ' ])
-> map ( ' strtoupper ' )
-> peekPrintR ()
-> foreach ( $ someComplexCallable ); print_r 의 각 항목.
$stream->printR(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> printR ();
// print_r output 스트림에있는 각 항목을 var_dump .
$stream->varDump(): void
use IterTools Stream ;
$ items = [ $ string , $ array , $ object ];
Stream:: of ( $ words )-> varDump ();
// var_dump output Itertools를 결합하여 새로운 반복 가능한 구성을 만들 수 있습니다.
use IterTools Multi ;
use IterTools Single ;
$ letters = ' ABCDEFGHI ' ;
$ numbers = ' 123456789 ' ;
foreach (Multi:: zip (Single:: string ( $ letters ), Single:: string ( $ numbers )) as [ $ letter , $ number ]) {
$ battleshipMove = new BattleshipMove( $ letter , $ number )
}
// A1, B2, C3 use IterTools Multi ;
use IterTools Single ;
$ letters = ' abc ' ;
$ numbers = ' 123 ' ;
foreach (Multi:: chain (Single:: string ( $ letters ), Single:: string ( $ numbers )) as $ character ) {
print ( $ character );
}
// a, b, c, 1, 2, 3 옵션이 있으면 기본값은 엄격한 유형 비교를 수행합니다.
유형 강요 (비 스트릭 유형)가 사용 가능하고 선택적 플래그를 통해 활성화 된 경우 :
Itertools PHP는 다음 표준을 준수합니다.
Itertools PHP는 MIT 라이센스에 따라 라이센스가 부여됩니다.
IterTools 기능은 PHP 및 Python에만 국한되지 않습니다. Other languages have similar libraries. Familiar functionality is available when working in other languages.