Search code examples
phphtmlforeachlaravel-bladelaravel-5.3

Html code for a foreach


my problem is that I have a foreach inside another foreach and the data that should appear are 3 but I get triple, this happens since I have two tables and I'm trying to get specific data from the first table are selected, this information I have it in the second table, so the repetition of the html code, if someone could give me an idea or even give me the solution to this problem would be much appreciated

My html:

<div class="form-group form-animate-text">
    <h4>Alumnos</h4>
    <select class="selectpicker form-control" multiple data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" name="alumno_id[]">
       @foreach($alumnoDB as $fila)
          @foreach($datosEvaluacionAlumno as $filaEvaluacionAlumno)
              <option value="{{$fila->id}}" {{($filaEvaluacionAlumno->alumno_id == $fila->id) ? 'selected=selected' : ""}}>{{$fila->nombre_alumno}}</option>
          @endforeach
       @endforeach
   </select>
</div>

It would be very helpful if someone knew how to solve it or at least have an idea of ​​the solution


Solution

  • Use only one foreach

    <div class="form-group form-animate-text">
    <h4>Alumnos</h4>
    <select class="selectpicker form-control" multiple data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" name="alumno_id[]">
       <?php 
       $i=0;
       ?>
       @foreach($alumnoDB as $fila)
    
              <option value="{{$fila->id}}" {{($filaEvaluacionAlumno[$i]->alumno_id == $fila->id) ? 'selected=selected' : ""}}>{{$fila->nombre_alumno}}</option>
           <?php $i=$i+1; ?>
    
       @endforeach
    

    No sure, and correct syntax but you can alter and do something like this. I did not get your requirement clearly. But you can use a index variable and use second array accordingly with that index variable ($i).

    Or you can do like

    <div class="form-group form-animate-text">
    <h4>Alumnos</h4>
    <select class="selectpicker form-control" multiple data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" name="alumno_id[]">
    <?php 
    $selected_text = "";
    $flag_idex ="";
    $i = 0;
    ?>
    @foreach($alumnoDB as $fila)
      <?php 
        //for($i=0; $i<=count($filaEvaluacionAlumno);$i++){
            if($fila->id==$filaEvaluacionAlumno[$i]->alumno_id){
                $selected_text = "Selected";
            }
            else{
                $selected_text = " ";
            }
        //}
      ?>
      <option value="{{$fila->id}}" {{$selected_text}}>{{$fila->nombre_alumno}}</option>
      <?php $i=$i+1; ?>
    @endforeach