It is more elegant/expressive/modern/concise to use array_column()
instead of a foreach()
for this task.
The first parameter is the input array of rows.
The second parameter is the column to become the values in the output array.
The third parameter is the column to become the keys in the output array.
Code: (Demo)
$array = [
['id' => 1, 'key' => 'foo', 'data' => 'a'],
['id' => 2, 'key' => 'bar', 'data' => 'b'],
['id' => 3, 'key' => 'barf', 'data' => 'c'],
];
var_export(
array_column($array, 'data', 'id')
);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
The Laravel equivalent method to call on a collection is pluck()
like:
$collection->pluck('data', 'id')
If you'd like to assign new first level keys but leave the rows unchanged, you write null
as the second parameter of the native function call.
Code: (Demo)
var_export(
array_column($array, null, 'id')
);
Output:
array (
1 =>
array (
'id' => 1,
'key' => 'foo',
'data' => 'a',
),
2 =>
array (
'id' => 2,
'key' => 'bar',
'data' => 'b',
),
3 =>
array (
'id' => 3,
'key' => 'barf',
'data' => 'c',
),
)
A lesser realized, functionless technique would be to use array destructuring inside a body-less foreach()
loop. (Demo)
$array = [
['id' => 1, 'data' => 'a'],
['id' => 2, 'data' => 'b'],
['id' => 3, 'data' => 'c'],
];
$result = [];
foreach ($array as ['id' => $id, 'data' => $result[$id]]);
var_export($result);
This is equivalent to the earlier answers which advise this:
foreach ($array as $row) {
$result[$row['id']] = $row['data'];
}
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)