Home » Php » PHP, how to convert indexed array to associative array easily

PHP, how to convert indexed array to associative array easily

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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;

Answer:

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
    )

)

Answer:

Poor me need to implement this in PHP 5.2, and I do not want to use for loop

here’s my implementation:

        function getField($x) { return $x['name']; }
        $ids = array_map('getField', $result);
        $result = array_combine($ids, $result);

See if maybe this helps anybody lol

Answer:

The accepted answer is close, but “close” only counts with hand grenades.

($unique is an indexed array)

$sub_key = 'country';
$new_array = [];
foreach ($unique as $value) {
  $new_array[] = [$sub_key => $value];
}