Skip to content

Commit

Permalink
Introduce Arr::prependKeysWith helper (#42448)
Browse files Browse the repository at this point in the history
* Adding new Arr helper to prepend all associative array key names with a provided prefix.

* Undoing incorrect delete of phpunit.xml.dist

* use Collections for mapping the keys.

* replace helper function by Collection class

* typo

* fix styleCI issues

* fix styleCI issues
  • Loading branch information
denjaland authored May 19, 2022
1 parent e05f51a commit ffa6cca
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,20 @@ public static function keyBy($array, $keyBy)
return Collection::make($array)->keyBy($keyBy)->all();
}

/**
* Prepend the key names of an associative array.
*
* @param array $array
* @param string $prependWith
* @return array
*/
public static function prependKeysWith($array, $prependWith)
{
return Collection::make($array)->mapWithKeys(function ($item, $key) use ($prependWith) {
return [$prependWith.$key => $item];
})->all();
}

/**
* Get a subset of the items from the given array.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1076,4 +1076,25 @@ public function testKeyBy()
'498' => ['id' => '498', 'data' => 'hgi'],
], Arr::keyBy($array, 'id'));
}

public function testPrependKeysWith()
{
$array = [
'id' => '123',
'data' => '456',
'list' => [1, 2, 3],
'meta' => [
'key' => 1,
],
];

$this->assertEquals([
'test.id' => '123',
'test.data' => '456',
'test.list' => [1, 2, 3],
'test.meta' => [
'key' => 1,
],
], Arr::prependKeysWith($array, 'test.'));
}
}

0 comments on commit ffa6cca

Please sign in to comment.