0

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?

1 Answer 1

2

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

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.