Skip to content

Commit 46ff808

Browse files
authored
[10.x] Add Arr::mapWithKeys() (#47000)
* Add `Arr::mapWithKeys()` * Code style * Code style * Code style
1 parent 2cda78a commit 46ff808

File tree

3 files changed

+48
-11
lines changed

3 files changed

+48
-11
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,35 @@ public static function map(array $array, callable $callback)
563563
return array_combine($keys, $items);
564564
}
565565

566+
/**
567+
* Run an associative map over each of the items.
568+
*
569+
* The callback should return an associative array with a single key/value pair.
570+
*
571+
* @template TKey
572+
* @template TValue
573+
* @template TMapWithKeysKey of array-key
574+
* @template TMapWithKeysValue
575+
*
576+
* @param array<TKey, TValue> $array
577+
* @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
578+
* @return array
579+
*/
580+
public static function mapWithKeys(array $array, callable $callback)
581+
{
582+
$result = [];
583+
584+
foreach ($array as $key => $value) {
585+
$assoc = $callback($value, $key);
586+
587+
foreach ($assoc as $mapKey => $mapValue) {
588+
$result[$mapKey] = $mapValue;
589+
}
590+
}
591+
592+
return $result;
593+
}
594+
566595
/**
567596
* Push an item onto the beginning of an array.
568597
*

src/Illuminate/Collections/Collection.php

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -816,17 +816,7 @@ public function mapToDictionary(callable $callback)
816816
*/
817817
public function mapWithKeys(callable $callback)
818818
{
819-
$result = [];
820-
821-
foreach ($this->items as $key => $value) {
822-
$assoc = $callback($value, $key);
823-
824-
foreach ($assoc as $mapKey => $mapValue) {
825-
$result[$mapKey] = $mapValue;
826-
}
827-
}
828-
829-
return new static($result);
819+
return new static(Arr::mapWithKeys($this->items, $callback));
830820
}
831821

832822
/**

tests/Support/SupportArrTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,24 @@ public function testMap()
642642
$this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data);
643643
}
644644

645+
public function testMapWithKeys()
646+
{
647+
$data = [
648+
['name' => 'Blastoise', 'type' => 'Water', 'idx' => 9],
649+
['name' => 'Charmander', 'type' => 'Fire', 'idx' => 4],
650+
['name' => 'Dragonair', 'type' => 'Dragon', 'idx' => 148],
651+
];
652+
653+
$data = Arr::mapWithKeys($data, function ($pokemon) {
654+
return [$pokemon['name'] => $pokemon['type']];
655+
});
656+
657+
$this->assertEquals(
658+
['Blastoise' => 'Water', 'Charmander' => 'Fire', 'Dragonair' => 'Dragon'],
659+
$data
660+
);
661+
}
662+
645663
public function testMapByReference()
646664
{
647665
$data = ['first' => 'taylor', 'last' => 'otwell'];

0 commit comments

Comments
 (0)