0

I'm wondering how can I add attributes, that are not declared in a class, into an object.

Let me explain :

I have my order :

 [0] => stdClass Object
( 
   [quantityBlack] => 3
   [quantityBlue] => 1
   [quantityGreen] => 0
   [quantityOrange] => 0
   [quantityPurple] => 0
   [quantityRed] => 0
   [dateOfOrder] => Fri, 06 Jul 12 22:21
   [user_id] => 5
   [comments] => Test
)

and I would like to replace the user_id by the attributes of the user,

so what I would like to do is :

foreach ($data['orders'] as $key => $order){

        $data['orders']->$key???-> = $this->user_model->GetUsers(array('userId' => $order->user_id));

    }

but I don't know how to specifically target a single object (you see the key???) at the end, I would like to get the attributes of the related user to that order.

How can I do that ?

Thank You !

madfriend
  • 2,400
  • 1
  • 20
  • 26
Miles M.
  • 4,089
  • 12
  • 62
  • 108

1 Answers1

3

If I understand correctly your data structure you are seeking to do the following:

foreach($data['orders'] as $key => $order) {
    $data['orders'][$key]->user = $this->user_model->GetUsers(array('userId' => $data['orders'][$key]->user_id));
    unset($data['orders'][$key]->user_id);
}

I'm assuming $data['orders'] is an array containing a bunch of stdClass objects like the one referenced in the question, hence why in this case you would use the $data['orders'][$key] syntax to access each array element first before accessing the properties of each object.

Note that both the data structure and your intent in the question are a bit unclear though, so if this doesn't address your question you may want to give more context.

Mahn
  • 16,261
  • 16
  • 62
  • 78
  • Yes exactly, thx very much, It's exactly the structure I was looking for. – Miles M. Jul 20 '12 at 15:45
  • Also note (since I forgot to mention it) that since what you have are stdClass objects, you can add the "user" property dynamically as you go, but don't expect the same behaviour with other kind of objects (not an issue for what you need now but it's good to know) – Mahn Jul 20 '12 at 15:47
  • where can I have a list/description of all types of Objects ? I wasn't aware there are != types of objects .. – Miles M. Jul 20 '12 at 16:34
  • Normally you would define the objects yourself, stdClass just happens to be a "magic" php class (see: http://stackoverflow.com/questions/931407/what-is-stdclass-in-php) – Mahn Jul 20 '12 at 16:48