-2

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

dmgig
  • 4,400
  • 5
  • 36
  • 47
  • 1
    Possible duplicate of [PHP's array\_map including keys](https://stackoverflow.com/questions/13036160/phps-array-map-including-keys) – marekful Aug 01 '18 at 18:13
  • Why you don't want to use a `foreach`? – nice_dev Aug 01 '18 at 18:15
  • @vivek_23 I just wanted a one liner if possible. All I could come up with was 4 lines. – dmgig Aug 01 '18 at 18:23
  • Is this a lousy question for stack overflow? – dmgig Aug 01 '18 at 18:25
  • @marekful I don't see how it's the same. They aren't maintaining the keys in the output array, their desired output puts the original keys inside the new array values. – dmgig Aug 01 '18 at 18:29
  • @dgig Is 2 liners ok ? It uses foreach though. – nice_dev Aug 01 '18 at 18:30
  • I don't really care, I guess I was hoping to find there was some variation of array_map or some PHP function that would allow it to be done. – dmgig Aug 01 '18 at 18:32
  • @dgig, I meant to indicate that that post deals with how to work around array_map's inability do handle keys. The plenty of answers there combined with a little imagination should kick you off on some good path. – marekful Aug 01 '18 at 19:25
  • @marekful I see, thank you. – dmgig Aug 01 '18 at 19:47

3 Answers3

4

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
)
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
0

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);
nice_dev
  • 17,053
  • 2
  • 21
  • 35
0
$json = '[
    { "id": 2, "name": "Suzy" },
    { "id": 3, "name": "Joe" },
    { "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');