-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

9
  • 1
    Possible duplicate of PHP's array_map including keys Commented Aug 1, 2018 at 18:13
  • Why you don't want to use a foreach? Commented Aug 1, 2018 at 18:15
  • @vivek_23 I just wanted a one liner if possible. All I could come up with was 4 lines. Commented Aug 1, 2018 at 18:23
  • Is this a lousy question for stack overflow? Commented Aug 1, 2018 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. Commented Aug 1, 2018 at 18:29

3 Answers 3

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

This is great. It isn't json, just an array of objects. I didn't know another way to show it. But this looks good to me. Thank you.
Note this should work as is on objects if they implement ArrayAccess.
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);

Comments

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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.