phparrayslaravellaravel-collection

How to apply custom keys to my sequential array/collection of arrays using Laravel or PHP?


I'm trying to apply custom keys to a collection in laravel.

The best way that I found was using functions like transform or mapWithKeys.

$result = $collection->map(function ($item) {
    return [
        'custom_key_name_1' => $item[0],
        'custom_key_name_2' => $item[1],
        'custom_key_name_3' => $item[2],
    ];
});

I was hoping to find something like:

$keys = ['custom_key_name_1', 'custom_key_name_2', 'custom_key_name_3'];
result = $collection->withKeys($keys);

Do you know any other way to do that with a less verbose code?

I'm working in a legacy Laravel 5.5 project.

Input Example

$collection = collect([
    [ 'first', 'second', 'third' ],
    [ '1', '2', '3' ],
    [ '1st', '2nd', '3rd' ],
]);

Expected Output

[
  [
    'custom_key_name_1' => 'first',
    'custom_key_name_2' => 'second',
    'custom_key_name_3' => 'third',
  ],
  [
    'custom_key_name_1' => '1',
    'custom_key_name_2' => '2',
    'custom_key_name_3' => '3',
  ],
  [
    'custom_key_name_1' => '1st',
    'custom_key_name_2' => '2nd',
    'custom_key_name_3' => '3rd',
  ],
]

Solution

  • Since you're working with a collection of arrays, you can use PHP's array_combine() method to put the keys and values together:

    $collection = collect([
        [ 'first', 'second', 'third' ],
        [ '1', '2', '3' ],
        [ '1st', '2nd', '3rd' ],
    ]);
    $keys = collect(['custom_key_name_1', 'custom_key_name_2', 'custom_key_name_3']);
    
    $result = $collection->map(fn ($v) => $keys->combine($v));
    
    dump($result);
    

    Result:

    Illuminate\Support\Collection^ {#5189
      #items: array:3 [
        0 => array:3 [
          "custom_key_name_1" => "first"
          "custom_key_name_2" => "second"
          "custom_key_name_3" => "third"
        ]
        1 => array:3 [
          "custom_key_name_1" => "1"
          "custom_key_name_2" => "2"
          "custom_key_name_3" => "3"
        ]
        2 => array:3 [
          "custom_key_name_1" => "1st"
          "custom_key_name_2" => "2nd"
          "custom_key_name_3" => "3rd"
        ]
      ]
      #escapeWhenCastingToString: false
    }
    

    The important caveat being that, per the documentation, "a ValueError is thrown if the number of elements in keys and values does not match."