Search code examples
phplaravellaravel-5laravel-collection

Laravel Collection. Map one keys to other


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

Solution

  • 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;
    });