YaLinqo\Enumerable::select PHP Method

select() public method

Syntax: select (selectorValue {(v, k) ==> result} [, selectorKey {(v, k) ==> result}])

This projection method requires the transform functions, selectorValue and selectorKey, to produce one key-value pair for each value in the source sequence. If selectorValue returns a value that is itself a collection, it is up to the consumer to traverse the subsequences manually. In such a situation, it might be better for your query to return a single coalesced sequence of values. To achieve this, use the {@link selectMany()} method instead of select. Although selectMany works similarly to select, it differs in that the transform function returns a collection that is then expanded by selectMany before it is returned.

public select ( callable $selectorValue, callable | null $selectorKey = null ) : Enumerable
$selectorValue callable {(v, k) ==> value} A transform function to apply to each value.
$selectorKey callable | null {(v, k) ==> key} A transform function to apply to each key. Default: key.
return Enumerable A sequence whose elements are the result of invoking the transform functions on each element of source.
    public function select($selectorValue, $selectorKey = null)
    {
        $selectorValue = Utils::createLambda($selectorValue, 'v,k');
        $selectorKey = Utils::createLambda($selectorKey, 'v,k', Functions::$key);
        return new self(function () use($selectorValue, $selectorKey) {
            foreach ($this as $k => $v) {
                (yield $selectorKey($v, $k) => $selectorValue($v, $k));
            }
        });
    }

Usage Example

Exemplo n.º 1
0
 /** {@inheritdoc} */
 public function getIterator()
 {
     $orders = [];
     for ($order = $this; $order != null; $order = $order->parent) {
         $orders[] = $order;
     }
     $orders = array_reverse($orders);
     $map = $this->source->select(function ($v, $k) {
         return ['v' => $v, 'k' => $k];
     })->toList();
     $comparers = [];
     for ($i = 0; $i < count($orders); ++$i) {
         $order = $orders[$i];
         $comparer = $order->comparer;
         if ($order->desc) {
             $comparer = function ($a, $b) use($comparer) {
                 return -$comparer($a, $b);
             };
         }
         $comparers[] = $comparer;
         for ($j = 0; $j < count($map); ++$j) {
             $keySelector = $order->keySelector;
             $map[$j][] = $keySelector($map[$j]['v'], $map[$j]['k']);
         }
     }
     usort($map, function ($a, $b) use($comparers) {
         for ($i = 0; $i < count($comparers); ++$i) {
             $diff = $comparers[$i]($a[$i], $b[$i]);
             if ($diff != 0) {
                 return $diff;
             }
         }
         return 0;
     });
     return Enumerable::from($map)->select(function ($v) {
         return $v['v'];
     }, function ($v) {
         return $v['k'];
     })->getIterator();
 }
All Usage Examples Of YaLinqo\Enumerable::select