PHP: Convert Object to Associative Array with Object Property as Key-ThrowExceptions

Exception or error:

In PHP, I’d like to convert an array of objects like the following to a PHP array, using one of the properties as the associative array keys.

[
  { "id": 2, "name": "Suzy" },
  { "id": 3, "name": "Joe" },
  { "id": 4, "name": "Sara" }
]

like this…

[
  2 => "Suzy",
  3 => "Joe",
  4 => "Sara"
]

I can’t use array_map because you can’t set the keys from my understanding, but I’m wondering if there’s a one-liner way to do it without a foreach loop.

To be clear, I want to maintain the keys in the output array, not puts the original keys inside the new array values like they do here: PHP's array_map including keys

How to solve:

It appears by “object” you mean a JSON object. Given that, you can use array_column() to pull out a single column from each row, and then array_combine() to use one column for the keys and another for the values:

$json = '[
    { "id": 2, "name": "Suzy" },
    { "id": 3, "name": "Joe" },
    { "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$out = array_combine(array_column($array, 'id'), array_column($array, 'name'));
print_r($out);

Yields:

Array
(
    [2] => Suzy
    [3] => Joe
    [4] => Sara
)

Answer:

2 liners and has a foreach though.

<?php

$json = '[
  { "id": 2, "name": "Suzy" },
  { "id": 3, "name": "Joe" },
  { "id": 4, "name": "Sara" }
]';

$new_array = [];
foreach(json_decode($json,true) as $each_object) $new_array[$each_object['id']] = $each_object['name'];

print_r($new_array);

Answer:

$json = '[
    { "id": 2, "name": "Suzy" },
    { "id": 3, "name": "Joe" },
    { "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');

Leave a Reply

Your email address will not be published. Required fields are marked *