首页 > 解决方案 > Laravel:当值与上一个值不同时如何移动新行,刀片中的foreach

问题描述

在进行循环过程时,我想比较当前值与先前值不同时,然后移动新行。

--------------------------
|unique_id| name | stats |
--------------------------
|1        | A    | P     |
|1        | B    | P     |
|1        | C    | P     |
|2        | D    | P     |
--------------------------

这是我在刀片中的代码:

@foreach ($result as $item)
  {{ $item->stats}}
@endforeach

结果: 在此处输入图像描述

标签: phplaravellaravel-5.8

解决方案


定义$previousstatus外部foreach。运行后foreach,该变量将设置 current 的值,status这将在下一次运行中对您有所帮助。

@php $previousstatus = ''; @endphp
@foreach ($result as $item)

 //@if($previousstatus == $item->stats) @endif do as you want with previousstatus

  {{ $item->stats}}

 @php $previousstatus =  $item->stats; @endphp //set the status for next loop becuase we need to remember in next loop what was the last element so store it in temp(previousstatus ) varible,

@endforeach

推荐阅读