-1

I have the object below:

    $user= 
    object(stdClass)(2) 
    { 
        ["questions"]=> object(stdClass)(1) { [0] => object(stdClass) } 
        ["num_root_responses_for_section"]=> string(1) "0" 
    }

I want add an object so that I will have an array of objects into the questions property.

$user->questions[] = $new_question_object;

Doesn't work as it isn't an array.

I want something like so:

object(stdClass)(2) 
    { 
        ["questions"]=> object(stdClass)(2) { 
            [0]=> object(stdClass), 
            [1]=> object(stdClass) }
        ["num_root_responses_for_section"]=> string(1) "0" 
    }

I understand that I can count it, increment the count, then add my object. Just looking for a better way.

allencoded
  • 7,015
  • 17
  • 72
  • 126

2 Answers2

0

You would be better using an array, and this is hackish but I was bored:

$n = max(array_keys(get_object_vars($user->questions)));
$user->questions->{$n+1} = $new_question_object;

Or shorter (not really):

$user->questions->{max(array_keys(get_object_vars($user->questions)))+1} = $new_question_object;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Since you insist on using objects you can do this..

$users->questions->{'9'} = 'value'; 

where 9 in this case is your preferred index for that item.

Kaspersky
  • 95
  • 1
  • 11