Collections: Include transformKeys method #38269
-
I would like to see a method that transforms keys, e.g. for converting them all to lower case (in case they're strings) or multiplying them by 2 (when it's an array). Example: $collection = collect([1, 2, 3]);
$collection->transformKeys(function($key) {
return $key * 2;
});
// [0 => 1, 2 => 2, 4 => 3]
$collection = collect([
'Content-Type' => 'application/json',
'X-MyApp-Access-Token' => 'abc123'
]);
$collection->transformKeys(function($key) {
return strtolower($key);
});
// [
// 'content-type' => 'application/json'
// 'x-myapp-access-token' => 'abc123'
// ] Currently I'm doing it by using $collection->flip()->transform(...)->flip() but that's not working for when two elements have different keys but the same value. |
Beta Was this translation helpful? Give feedback.
Answered by
dennisprudlo
Aug 8, 2021
Replies: 1 comment 1 reply
-
I would usually use $headers = collect([
'Content-Type' => 'application/json',
'X-MyApp-Access-Token' => 'abc123'
]);
$headers = $headers->mapWithKeys(fn ($value, $key) => [ strtolower($key) => $value ]); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
levu42
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would usually use
mapWithKeys
in such a case: