3

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',
 * ]
 */
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
D.R.
  • 2,540
  • 3
  • 24
  • 49

2 Answers2

4

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;
});
halfer
  • 19,824
  • 17
  • 99
  • 186
Rwd
  • 34,180
  • 6
  • 64
  • 78
  • Thank you, but looks like I have oversimplified. I have an associative array, not a simple one. I have updated an example. Could you help me with that? – D.R. Sep 07 '17 at 13:00
  • Thank you) I haven't used keyBy before and your solution with it is neat and quite pretty). – D.R. Sep 07 '17 at 13:29
1

Updated Answer

$resultCollection = $data->combine($mappedKeys);
Rahul Dhande
  • 483
  • 5
  • 9
  • Thank you. I have updated the answer, so your solution is outdated, but it was right in the beginning. I'm ready to add +1, if you update it :) – D.R. Sep 07 '17 at 17:08
  • Sorry, but your solution won't work. I've tried it. I thought you would rewrite your solution in php, so it could be helpful for other people, that don't use collections but have a similar issue. – D.R. Sep 09 '17 at 12:59