Laravel Collection. Map one keys to other

10.2k views Asked by At

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',
 * ]
 */
2

There are 2 answers

2
Rwd On BEST ANSWER

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;
});
5
Rahul Dhande On

Updated Answer

$resultCollection = $data->combine($mappedKeys);