2

I am getting an array from table questions

$questions = Category::where('slug', $slug)->first()->questions->toArray();

then using foreach I iterate over array and push an array element during each iteration like below

foreach ($questions as $question) {
        $question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
    }

Ideally I should get response like below

array (size=5)
0 => 
array (size=6)
  'id' => int 1
  'category_id' => int 1
  'questions' => string 'The ozone layer restricts' (length=25)
  'answer_id' => int 4
  'image_path' => string '' (length=0)
  'options' => 
    array (size=4)
      0 => 
        array (size=3)
          ...
      1 => 
        array (size=3)
          ...
      2 => 
        array (size=3)
          ...
      3 => 
        array (size=3)
          ...
1 => 
array (size=6)
  'id' => int 2
  'category_id' => int 1
  'questions' => string 'Ecology deals with' (length=18)
  'answer_id' => int 10
  'image_path' => string '' (length=0)
  'options' => 
    array (size=4)
      0 => 
        array (size=3)
          ...
      1 => 
        array (size=3)
          ...
      2 => 
        array (size=3)
          ...
      3 => 
        array (size=3)
          ...

but Actually I am not getting options key into my questions array

3 Answers 3

1

The issue here is when you do a foreach, you are referring to the array by value - that is, under the hood PHP will create a copy of the variable inside the array. What you need is to access each element in the foreach by reference (note the & next to $q)

foreach ($questions as & $q) {
        $q['options'] = Option::where('question_id', '=', $q['id'])->get()->toArray();
}

See: Passing by references and the PHP docs on foreach.

Note: This is not really a Laravel issue, just PHP.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this (& in foreach):

foreach ($questions as & $question) {
        $question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
}

Comments

1

You can try:

foreach ($questions as $key=>$question) {
    $questions[$key]['options'] = Option::where('question_id',$question['id'])->get()->toArray();
}

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.