Jack Coolen Jack Coolen - 5 months ago 29
PHP Question

Convert an array filled with objects

I have an array that give objects back like this:

array (size=61)
0 =>
private 'id' => int 53
private 'name' => string 'Volkswagen' (length=10)
1 =>
private 'id' => int 43
private 'name' => string 'Toyota' (length=6)
2 =>
private 'id' => int 32
private 'name' => string 'BMW' (length=3)

How can I convert the array to so that the id become the key and the value the description, like this:

array (size=61)
53 => 'Volkswagen'
43 => 'Toyota'
32 => 'BMW'

I've tried

$cars = array();
foreach ($result as $key => $value) {
$cars[$value['id']] = $value['name'];

But that doesn't work.


You are treating your objects as if they were arrays.

$array['key'] is the notation for accessing an element in an array, but $object->key is the one for an object.

Try this :

$cars = array();    
foreach ($result as $key => $value) {
    $cars[$value->id] = $value->name;

EDIT : If that doesn't work (due to the private nature of the elements), you might have to declare functions like getID() and getName() in your object class file, and use them as such :

$cars = array();    
foreach ($result as $key => $value) {
    $cars[$value->getID()] = $value->getName();