PHP, how to convert indexed array to associative array easily
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
)
)
You can simply do this
$input = [
["id" => 1, "name" => "a1"],
["id" => 2, "name" => "a2"]
];
$result = array_merge(
...array_map(
fn($item) => [$item['name'] => $item],
$input
)
);
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;