Erik van de Ven Erik van de Ven - 4 months ago 78
PHP Question

array_column with an array of objects

I would like to set the keys, of an array with objects, to a value of the object. So this array:

$array = Array
(
[0] => stdClass Object
(
[id] = 12234
[value] = some value
)

[1] => stdClass Object
(
[id] = 12994
[value] = some value
)

)


Should become:

$array = Array
(
[12234] => stdClass Object
(
[id] = 12234
[value] = some value
)

[12994] => stdClass Object
(
[id] = 12994
[value] = some value
)

)


Now I could loop over the array, but I would prefer a more cleaner solution. I thought this should work:

$newArray = array_column($array, null, 'id');


The only problem is I'm having an array of objects instead of an array of arrays and I'm not using PHP7 yet. Now I found a similar question over here
PHP. Is it possible to use array_column with an array of objects

But the thing is it doesn't return what I expected. Cause this:

$newArray = array_map(function($o) {
return is_object($o) ? $o->id : $o['id'];
}, $array);


Returns

Array
(
[0] => 12234
[1] => 12994
)


Anyone who knows a clean solution (so without a for or foreach loop) for this?

Answer
$array = array_combine(array_map(function ($o) { return $o->id; }, $array), $array);

Whether this is really a lot better than a simple foreach loop, aside from "but, but, functional programming...!", is debatable.

Comments