Jack Coolen Jack Coolen - 18 days ago 5
PHP Question

Convert an array filled with objects

I have an array that give objects back like this:

array (size=61)
0 =>
object(Xxx\Car)[602]
private 'id' => int 53
private 'name' => string 'Volkswagen' (length=10)
1 =>
object(Xxx\Car)[594]
private 'id' => int 43
private 'name' => string 'Toyota' (length=6)
2 =>
object(Xxx\Car)[595]
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.

Answer

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();
}