Groups elements from an iterator based on a callback function.
Description
This iterator aggregates elements into associative arrays where the keys are
determined by a user-defined function ($groupBy). Each key contains an array
of elements that share the same computed group.
Usage Example:
Description
Grouping by age
use FastForward\Iterator\GroupByIteratorIterator;
use ArrayIterator;
$data = new ArrayIterator([
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 25],
]);
$grouped = new GroupByIteratorIterator($data, fn($item) => $item['age']);
foreach ($grouped as $age => $group) {
echo "Age: $age\n";
print_r($group);
}
// Outputs:
// Age: 25
// [['name' => 'Alice', 'age' => 25], ['name' => 'Charlie', 'age' => 25]]
// Age: 30
// [['name' => 'Bob', 'age' => 30]]
Note: The iterator must be rewound before iterating again to ensure correct grouping.
Properties
Methods
Initializes the GroupByIteratorIterator.
Counts the number of elements exposed by the inner iterator.
Retrieves the current group of elements.
Retrieves the key of the current group.
Advances to the next group in the iterator.
Rewinds the iterator and reprocesses the grouping.
Checks if the current position is valid.
Initializes the GroupByIteratorIterator.
public
__construct(
iterable<string|int, mixed>
$iterator, Closure
$groupBy) : mixed
Parameters
$iterator
:
iterable<string|int, mixed>
Description
the iterator containing values to be grouped
$groupBy
:
Closure
Description
a function that determines the group key for each element
Counts the number of elements exposed by the inner iterator.
public
count() : int
Description
If the inner iterator implements Countable, this method SHALL return the value provided by that implementation. Otherwise, it MUST count elements by iterating over the iterator. If the inner iterator is not cloneable, this method SHALL wrap the current object in an IteratorIterator instance and count through that wrapper to avoid performing an invalid clone operation. If the inner iterator is cloneable, this method SHOULD count over a clone so that the original iterator state is preserved as much as possible.
Return values
Description
the total number of elements available from the inner iterator
Retrieves the current group of elements.
public
current() : array<int, mixed>
Return values
Description
the current group of elements
Retrieves the key of the current group.
public
key() : mixed
Return values
Description
the computed key representing the current group
Advances to the next group in the iterator.
public
next() : void
Rewinds the iterator and reprocesses the grouping.
public
rewind() : void
Description
This ensures that the grouping is correctly recomputed when the iterator is reset.
Checks if the current position is valid.
public
valid() : bool
Return values
Description
true if a valid group exists, false otherwise