What's the easiest way to convert
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
to
$b = array(
"a1" => array("id" => 1, "name" => "a1"),
"a2" => array("id" => 2, "name" => "a2")
);
I was expecting PHP have some functional programming facilities to do something like:
$b = map($a, function($item) {
return $item["name"];
});
But I didn't find one.
You can use PHP array_column()
function. For your use case, the second argument should be null
to return the full array.
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
$b = array_column($a, null, 'name');
and print_r($b)
will result in
Array
(
[a1] => Array
(
[id] => 1
[name] => a1
)
[a2] => Array
(
[id] => 2
[name] => a2
)
)
The only solution I see is to loop through the array and create a new array manually.
For example, like this:
$new_array = [];
foreach ($array as $value)
$new_array[$value['name']] = $value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With