Parkour\Transform::combine PHP Method

combine() public static method

Indexes an array depending on the values it contains.
public static combine ( array $data, callable $cb, boolean $overwrite = true ) : array
$data array Data.
$cb callable Function to combine values.
$overwrite boolean Should duplicate keys be overwritten ?
return array Indexed values.
    public static function combine(array $data, callable $cb, $overwrite = true)
    {
        $combined = [];
        foreach ($data as $key => $value) {
            $Combinator = call_user_func($cb, $value, $key);
            $index = $Combinator->key();
            if ($overwrite || !isset($combined[$index])) {
                $combined[$index] = $Combinator->current();
            }
        }
        return $combined;
    }

Usage Example

 /**
  *
  */
 public function testCombine()
 {
     $users = [['id' => 1, 'name' => 'a'], ['id' => 2, 'name' => 'b'], ['id' => 3, 'name' => 'b']];
     $closure = function ($user) {
         (yield $user['name'] => $user['id']);
     };
     $expected = ['a' => 1, 'b' => 3];
     // overwriting existing names
     $this->assertEquals($expected, Transform::combine($users, $closure));
     $expected = ['a' => 1, 'b' => 2];
     // not overwriting existing names
     $this->assertEquals($expected, Transform::combine($users, $closure, false));
 }
All Usage Examples Of Parkour\Transform::combine