Alec
Alec

Reputation: 2154

Set one of the deep values of an array to be the key

Background

Say you have an array that looks like this, and we know that the id value is unique:

[
    0 => [
        'id' => 5,
        'name' => 'First item'
    ],
    1 => [
        'id' => 10,
        'name' => 'Second item',
    ],

    ...
]

Question

Is there a way to map this array to one that places the id value as the key, while keeping the rest of the value intact?

Desired result

Noticing now that the keys of the array matches the id value, the ideal result would be:

[
    5 => [
        'id' => 5,
        'name' => 'First item'
    ],
    10 => [
        'id' => 10,
        'name' => 'Second item'
    ]

    ...
]

Minor detail

For my purposes, whether or not the id key/value pair still exists in the array is unimportant, but I expect that if a solution exists to one case, the other solution would not differ by much.

Upvotes: 1

Views: 44

Answers (2)

Karol Oracz
Karol Oracz

Reputation: 182

Loop approach:

$newArray = [];
foreach ($array as $k => $v) {
    $newArray[$v['id']] = $v;
}

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

There's a built-in array function for that:

$result = array_column($array, null, 'id');

If id doesn't exist in a sub-array then it will increment from the previous and may be overwritten if that key is an id later.

Upvotes: 3

Related Questions