Reputation: 1051
How can I create an object inside a object inside a for loop? This is what I have, I want to be able to add another entry into this object every time the for loop happens but with an incremented number each time
for ($i = 0; $i <= $question->rank; $i++) {
$question->opciones = [
'id' => $i,
'option' => $i
];
}
I want that to look like this inside $question
{
"id":4,
"question":"question?",
"user_id":1,
"survey_section_id":2,
"response_type_id":3,
"optional":0,
"num":null,
"rank":6,
"show_text":1,
"created_at":"2019-12-10 08:22:37",
"updated_at":"2019-12-10 08:22:37",
"opciones":[
{
"id":1,
"option":1
},
{
"id":2,
"option":2
},
{
"id":3,
"option":3
},
{
"id":4,
"option":4
},
{
"id":5,
"option":5
},
{
"id":6,
"option":6
}
]
}
The current output is just this
{
"id":4,
"question":"question?",
"user_id":1,
"survey_section_id":2,
"response_type_id":3,
"optional":0,
"num":null,
"rank":6,
"show_text":1,
"created_at":"2019-12-10 08:22:37",
"updated_at":"2019-12-10 08:22:37",
"opciones":[
{
"id":1,
"option":1
}
]
}
What am I doing wrong?
Upvotes: 0
Views: 474
Reputation: 14921
You are overwriting the opciones
property every time.
Replace with this to append to the array instead of overwriting it:
$question->opciones[] = [
'id' => $i,
'option' => $i
];
Upvotes: 2