Search code examples
phparrayslaravellaravel-collection

Laravel/PHP renaming associative keys without knowing their names


Given following collection/array:

[
    "somename" => "test.test.be"
    "anothername" => "test"
    "yetanothername" => "testing"
    "extrafield" => "extra",
    "extrafield" => "extra",

]

When i retrieve this collection i always know the order of them, but i will not know the key-names. So what i want to do is transform this collection and change the keynames to my defined values.

For a non-associative array i would do something like

    $trimmedCollection->transform(function ($item) {
        return [
            'email'               => $item[0],
            'first_name'          => $item[1],
            'surname'             => $item[2],
        ];
    });

But how would i handle this for the given collection? Also what to do with overflow items. Say i suddenly got 10 key-value pairs but only wrote a transform for 3 how would i transform all the overflow to a default key?

Edit: For the overflow items i would like to assign all extra fields in the given array to be stored like so.

Below would be the final array:

[
    "email" => "test.test.be"
    "first_name" => "test"
    "surname" => "testing"
    "additional_fields" => ["key-name" => "extra","key-name" => "extra"]

]

Where the key-name is the original name of the key i retrieved.


Solution

  • You can use array_shift to remove the 1st element in the array for every known element, and add the remaining array to your additional_fields key:

    $trimmedCollection->transform(function ($item) {
    
        return [
            'email'               => array_shift($item), //$item[0]
            'first_name'          => array_shift($item), //$item[1]
            'surname'             => array_shift($item), //$item[2]
            'additional_fields'   => $item //all remaining items
        ];
    });