search

Home  >  Q&A  >  body text

How to access array elements in foreach loop in Laravel

I created a custom array to store the questions and answers, but whenever I try to access these array elements it gives me Trying to read the property "questions" on the array (

Actually, I have created a custom array. When I try to create without custom array it works fine. Like getting data from direct eloquent model works fine

This is my JSON response...

@foreach ($questionsArray as $i => $data)
                              <div class=" p-3 m-1 text-left">
                                <p class="font-weight-bold">Q.{{$i + 1}} {{$data->question}}</p>
                              // error is here !
                              
                              @endforeach
$questionsArray = array();

        foreach ($questions as $question) {

            $answers = tbl_answer::where('answer_question_table_id', $question->question_id)->get();
            $questionsArray[] = array(
                "question" => array($question),
                "answers"  => array($answers)
            );
        }

P粉312195700P粉312195700439 days ago564

reply all(1)I'll reply

  • P粉004287665

    P粉0042876652023-09-11 12:16:13

    Associative arrays and objects are not the same thing in php.

    Here you are pushing an array with keys question and answers into a questionsArray:

    $questionsArray[] = array(
                    "question" => array($question),
                    "answers"  => array($answers)
                );

    So you should use array access to read it. Assuming $data is an element of $questionsArray, you will have {{ $data['question'] }} instead of { { $data ->Question}}

    Of course, you've wrapped some question entities or associative arrays in another array and put it into $data['question]`, so the printout won't work.

    Maybe try something like this:

    $questionsArray[] = [
                    "question" => $question,
                    "answers"  => $answers
                ];

    Then read the properties of the problem in the blade file:

    @foreach ($questionsArray as $i => $data)
    
        <div class=" p-3 m-1 text-left">
        <p class="font-weight-bold">Q.{{$i + 1}} {{$data['question']['question_title']}}</p>
                                  
    @endforeach

    reply
    0
  • Cancelreply