Home > Mobile >  How to remove repetitive values from foreach loop in php
How to remove repetitive values from foreach loop in php

Time:05-08

Greetings I have an array of sections and the question related to that section looks like this

Image of array

And I loop through that array and output the content to the screen here is the code

 @foreach($sections as $section)
                    <div >
                        <h2>{{ $section['section_name'] }}</h2>
                        <p>{{ $section['section_description'] }}</p>
                        <p>{{ $section['section_intro'] }}</p>
                    </div>
                    <div >
                        @foreach($section['question'] as $question)
                            <h5>{{ $question['question_name'] }}</h5>
                            <p >{{ $question['question_description'] }}</p>
                        @endforeach
                    </div>
                @endforeach

And the result of that looks like this

Result of the foreach loop

How can I remove this duplicate question_name I just want it to write it once, for example, it writes one Key Contracts and this two question_description under there for all of them?

CodePudding user response:

 @foreach($sections as $section)
     <div >
         <h2>{{ $section['section_name'] }}</h2>
         <p>{{ $section['section_description'] }}</p>
         <p>{{ $section['section_intro'] }}</p>
     </div>
     <div >
         @php
             $questions = [];
             foreach($section['question'] as $question){
                 $questions[$question['question_name']][] = $question['question_description'];
             }
         @endphp
         @foreach($questions as $question_name=>$question_descriptions)
             <h5>{{ $question_name }}</h5>
             @foreach($question_descriptions as $question_description)
                 <p >{{ $question_description }}</p>
             @endforeach
         @endforeach
     </div>
 @endforeach

I haven't tried it but I think it will work. I'm storing the questions and descriptions in an array where the key is not an index but the name.

CodePudding user response:

You could perhaps map the questions into groups by question name before sending to view. Something like this (for example purposes to get you started):

$sections = collect($sections)->map(function($section, $key){
  return [
    "section" => $section,
    "grouped_questions"=> collect($section["question"])->mapToGroups(function($question, $key){
       return [$question['question_name'] => $question];
     })->toArray()
  ];
});

This will give you the questions grouped by their name.

  • Related