sort()¶
The sort operator processes a stream source and yields items ordered by keys or values. Ordering may be defined by a user-supplied comparator or by the default comparator, which relies on the spaceship operator (<=>) for key or value comparison.
Warning
The memory consumption of this operator depends on the number of items in the stream and it is considered as memory unsafe.
- class RunOpenCode\Component\Dataset\Operator\Sort¶
- __construct(iterable<TKey, TValue> $source, ?callable(TKey|TValue, TKey|TValue): int $comparator = null, bool $byKeys = false)¶
- Parameters:
$source –
iterable<TKey, TValue>Stream source to iterate over.$comparator –
?callable(TKey|TValue, TKey|TValue): intUser defined callable to compare two items. Ifnull, spaceship operator (<=>) is used.$byKeys –
boolIf$byKeysistrue, keys will be compared instead of values.
- getIterator()¶
- Returns:
\Traversable<TKey, TValue>Sorted items from the stream source.
Use cases¶
When items from stream needs to be sorted, either by keys or by values.
Example¶
1<?php
2
3use RunOpenCode\Component\Dataset\Stream;
4
5// Sort by values.
6new Stream(['a' => 3, 'b' => 1, 'c' => 2])
7 ->sort(
8 comparator: static fn(int $first, int $second): int => $first <=> $second,
9 byKeys: false,
10 );
11
12// Sort by keys.
13new Stream(['a' => 3, 'b' => 1, 'c' => 2])
14 ->sort(
15 comparator: static fn(string $first, string $second): int => \strcmp($first, $second),
16 byKeys: true,
17 );