0

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.

1
  • try storing the key and val in an intermediate variable first Commented Nov 18, 2016 at 13:01

2 Answers 2

5

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

Comments

0

Use the $arr = get_object_vars($obj); function. It converts an object to an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.