'How to remove repetitive values from foreach loop in php

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 class="form-group">
                        <h2>{{ $section['section_name'] }}</h2>
                        <p>{{ $section['section_description'] }}</p>
                        <p>{{ $section['section_intro'] }}</p>
                    </div>
                    <div class="form-group ms-5">
                        @foreach($section['question'] as $question)
                            <h5>{{ $question['question_name'] }}</h5>
                            <p class="ms-3">{{ $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?



Solution 1:[1]

 @foreach($sections as $section)
     <div class="form-group">
         <h2>{{ $section['section_name'] }}</h2>
         <p>{{ $section['section_description'] }}</p>
         <p>{{ $section['section_intro'] }}</p>
     </div>
     <div class="form-group ms-5">
         @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 class="ms-3">{{ $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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CleverSkull
Solution 2