Skip to content

Commit

Permalink
[10.x] Add Arr::mapWithKeys() (#47000)
Browse files Browse the repository at this point in the history
* Add `Arr::mapWithKeys()`

* Code style

* Code style

* Code style
  • Loading branch information
ralphjsmit authored May 9, 2023
1 parent 2cda78a commit 46ff808
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 11 deletions.
29 changes: 29 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,35 @@ public static function map(array $array, callable $callback)
return array_combine($keys, $items);
}

/**
* Run an associative map over each of the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @template TKey
* @template TValue
* @template TMapWithKeysKey of array-key
* @template TMapWithKeysValue
*
* @param array<TKey, TValue> $array
* @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
* @return array
*/
public static function mapWithKeys(array $array, callable $callback)
{
$result = [];

foreach ($array as $key => $value) {
$assoc = $callback($value, $key);

foreach ($assoc as $mapKey => $mapValue) {
$result[$mapKey] = $mapValue;
}
}

return $result;
}

/**
* Push an item onto the beginning of an array.
*
Expand Down
12 changes: 1 addition & 11 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -816,17 +816,7 @@ public function mapToDictionary(callable $callback)
*/
public function mapWithKeys(callable $callback)
{
$result = [];

foreach ($this->items as $key => $value) {
$assoc = $callback($value, $key);

foreach ($assoc as $mapKey => $mapValue) {
$result[$mapKey] = $mapValue;
}
}

return new static($result);
return new static(Arr::mapWithKeys($this->items, $callback));
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,24 @@ public function testMap()
$this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data);
}

public function testMapWithKeys()
{
$data = [
['name' => 'Blastoise', 'type' => 'Water', 'idx' => 9],
['name' => 'Charmander', 'type' => 'Fire', 'idx' => 4],
['name' => 'Dragonair', 'type' => 'Dragon', 'idx' => 148],
];

$data = Arr::mapWithKeys($data, function ($pokemon) {
return [$pokemon['name'] => $pokemon['type']];
});

$this->assertEquals(
['Blastoise' => 'Water', 'Charmander' => 'Fire', 'Dragonair' => 'Dragon'],
$data
);
}

public function testMapByReference()
{
$data = ['first' => 'taylor', 'last' => 'otwell'];
Expand Down

0 comments on commit 46ff808

Please sign in to comment.