Christophvh
Christophvh

Reputation: 13224

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.

Upvotes: 1

Views: 2184

Answers (2)

Steve
Steve

Reputation: 20469

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

Upvotes: 3

Sandeesh
Sandeesh

Reputation: 11906

You could do something like this to transform your selected keys. This retains the other values with their unchanged keys.

function replace_array_key(array &$item, $oldKey, $newKey)
{
    $item[$newKey] = $item[$oldKey];
    unset($item[$oldKey]);
}

$trimmedCollection->transform(function ($item) {
    replace_array_key($item, 'somename', 'email');
    replace_array_key($item, 'anothername', 'first_name');
    replace_array_key($item, 'yetanothername', 'surname');

    return $item;
});

You can even extend this to an array list of old and new key names and run it through and arrap_map.

Upvotes: 2

Related Questions