indexBy()

IndexBy operator iterates over given stream source and applies callable function to generate new keys for the resulting stream.

class RunOpenCode\Component\Dataset\Operator\IndexBy
__construct(iterable<TKey, TValue> $source, callable(TValue, TKey): TModifiedKey $callable)
Parameters:
  • $source – iterable<TKey, TValue> Stream source to iterate over.

  • $callable – callable(TValue, TKey): TModifiedKey Callable function to generate new keys for the resulting stream.

getIterator()
Returns:

\Traversable<TModifiedKey, TValue> Provided stream source or fallback stream source.

Use cases

  • Provide a simple way to index stream source by given callable function. Per example, when you iterate entities from database and you want to index them by their ID.

Example

Index entities by their ID.

1<?php
2
3use RunOpenCode\Component\Dataset\Stream;
4use Application\Model\MyEntity;
5
6new Stream($dataset)
7    ->indexBy(function(MyEntity $entity): int {
8        return $entity->getId();
9    }); // yields MyEntity with ID as key instead of 0, 1, 2, 3, ...