Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, how to convert indexed array to associative array easily

Tags:

arrays

php

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.

like image 206
user1633272 Avatar asked Mar 07 '17 14:03

user1633272


2 Answers

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
    )

)
like image 183
frz3993 Avatar answered Oct 12 '22 23:10

frz3993


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;
like image 20
Jerodev Avatar answered Oct 13 '22 01:10

Jerodev