Reputation: 2868
I want to map some keys in Laravel collection to other, that are stored in an array.
I can't "invent" a proper neat and short pipeline for such a transformation.
Here is a simplified example of what I want:
$mappedKeys = [
'1' => 'One',
'2' => 'Two',
'3' => 'Three',
'4' => 'Four',
];
$data = collect([
'1' => 'I',
'2' => 'II',
'3' => 'III',
'5' => 'V',
]);
$resultCollection = $data->...
/*
* I want to receive after some manipulations
*
* [
* 'One' => 'I',
* 'Two' => 'II',
* 'Three' => 'III',
* '5' => 'V',
* ]
*/
Upvotes: 3
Views: 11029
Reputation: 35180
You could always use the combine() method on the collection:
$mappedKeys = [
'1' => 'One',
'2' => 'Two',
'3' => 'Three',
'4' => 'Four',
];
$data = collect([
'1' => 'I',
'2' => 'II',
'3' => 'III',
'5' => 'V',
]);
$resultCollection = $data->keyBy(function ($item, $key) use ($mappedKeys) {
return isset($mappedKeys[$key]) ? $mappedKeys[$key] : $key;
});
Upvotes: 5
Reputation: 483
Updated Answer
$resultCollection = $data->combine($mappedKeys);
Upvotes: 1