Chunk数据和在Laravel视图中显示带标题的数据块



我有数据需要在Laravel刀片视图中显示在3行中,并带有标题。我知道Laravel中有一种chunk方法来对数据进行chunk和显示。但我想用不同的方式来展示数据。

这是我的数据

IlluminateSupportCollection {#1898 ▼
#items: array:2 [▼
0 => {#1021 ▼
+"parameter": "NH3 Examine"
+"id": 6
+"pond_quality_id": 5
+"parameter_id": 28
+"pond_water_cig": 12
+"pond_water_non_cig": 12
+"taken_actions_cig": 12
+"taken_actions_non_cig": 12
+"taken_actions": "action"
+"measure_before_intervention": "before"
+"measure_after_intervention": "after"
+"remarks": "remarks1"
+"created_at": "2021-04-25 10:16:00"
+"updated_at": "2021-04-25 10:16:00"
}
1 => {#1897 ▼
+"parameter": "O2 Examine"
+"id": 7
+"pond_quality_id": 5
+"parameter_id": 29
+"pond_water_cig": 23
+"pond_water_non_cig": 23
+"taken_actions_cig": 23
+"taken_actions_non_cig": 23
+"taken_actions": "action taken"
+"measure_before_intervention": "before intervention"
+"measure_after_intervention": "after intervention"
+"remarks": "remarks2"
+"created_at": "2021-04-25 10:16:00"
+"updated_at": "2021-04-25 10:16:00"
}
]
}

以下是我想要输出数据的方式

col1col2col3col4
col1 val1col2 val1col3 val3col4 val4
col1 val2col2 val2col3 val3col4 val4

您在刀片中使用的每个@foreach循环的作用域中都有$loop,它也会随着循环内的循环而扩展

下面是一个你如何实现你想要的东西的例子;每隔3行添加一个您选择的页眉。你可能需要处理那里的模数——我相信3是正确的,但考虑到$loop->iteration从1开始,而不是0,我可能错了。

请参阅:https://laravel.com/docs/8.x/blade有关@foreach上下文中$loop variable的更多用法

@foreach($items as $item)
@if($loop->iteration % 3 == 0)
//output header row
@endif
//output $item
@endforeach

您需要为标题行定义一组规则,考虑到您有3个相同的表,但第四个表似乎有1个标题并且是唯一的,您可能需要创建一个辅助函数,允许您在刀片中使用多个@if语句包含依赖于迭代的视图。

实现预期结果的更好方法是chunks函数。简单干净。

@foreach($items->chunk(2) as $chunk)
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>parameter</th>
<th>pond_quality_id</th>
<th>pond_water_cig</th>
</tr>
</thead>
<tbody>
@foreach($chunk as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->parameter}}</td>
<td>{{$item->pond_quality_id}}</td>
<td>{{$item->pond_water_cig}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endforeach

最新更新