How transform a php multidimensional array into a new array using the first column as key?
I'm trying to use an array function (I thought about array_map()
or array_walk()
, but couldn't get it to do what I want) in order to create an array using a multidimensional array (Like a MySQL result) turning a field from the array into the key of the new one.
Sa开发者_如何学运维y I have an array like this one:
$a = array(
0 => array( 'id' => 1, 'name' => 'john' ),
1 => array( 'id' => 28, 'name' => 'peter' )
);
And I'd like to get another array like this:
$b = array(
1 => array( 'name' => 'john' ),
28 => array( 'name' => 'peter' )
);
I can solve it with a simple foreach loop, but I wonder whether there's a more efficient way, using a built-in function.
array_map
and array_walk
don't allow you to change keys. A foreach loop is definitely the way to go. Foreach can even be more efficient than array_walk/array_map a lot of the time.
You Can use array_column function The Output its close to what you want
array_column($a, null, 'id')
This task can actually be done with a "body-less" foreach()
loop.
Using "array destructuing" to define variables and square-brace pushing syntax, the entire operation can be written in the foreach()
signature.
Code: (Demo)
$result = [];
foreach ($a as ['id' => $id, 'name' => $result[$id]['name']]);
var_export($result);
If a functional approach is preferred, then array_reduce()
is capable of writing first level keys to the output array.
Code: (Demo)
var_export(
array_reduce(
$a,
fn($result, $row) => array_replace($result, [$row['id'] => ['name' => $row['name']]]),
[]
)
);
精彩评论