foreach 每第 10 次和第 2 次更改
foreach with every 10th and 2nd changes
所以我正在处理需要打印的优惠券。我准备了视图并将优惠券传递给视图:
public function printSelected($ids){
$couponIDs = explode(',', $ids);
$selectedCoupons = Coupon::find($couponIDs);
return view('admin.coupons.print')->with(compact('selectedCoupons'));
}
现在我需要以某种方式遍历它们。
每 10 张优惠券我需要一个新的 "page" 块,因为 10 张优惠券适合一个页面块
每隔两张优惠券我需要一个新的 table 行,因为 2 张优惠券或 table 数据适合一行
有多种方法可以做到这一点,但我发现使用 Collection
对象的 chunk
方法非常可读。另一种选择是使用模数 ($index % 10 === 0
).
<div class="coupons">
{{-- Create chunks of 10 as this is the max per page --}}
@foreach($selectedCoupons->chunk(10) as $pageCoupons)
<div class="page">
<div class="subpage">
<table>
{{-- Create chunks of 2 so every row is filled with up to 2 coupons --}}
@foreach($pageCoupons->chunk(2) as $rowCoupons)
<tr>
{{-- Loop over the row coupons to create the columns --}}
@foreach($rowCoupons as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
@endforeach
</tr>
@endforeach
</table>
</div>
</div>
@endforeach
</div>
您可以使用集合的 chunk
方法来遍历您的优惠券块:
<div class="coupons">
@foreach ($selectedCoupons->chunk(10) as $page)
<div class="page">
<div class="subpage">
<table>
@foreach ($page->chunk(2) as $row)
<tr>
@foreach ($row as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
@endforeach
</tr>
@endforeach
</table>
</div>
</div>
@endforeach
</div>
所以我正在处理需要打印的优惠券。我准备了视图并将优惠券传递给视图:
public function printSelected($ids){
$couponIDs = explode(',', $ids);
$selectedCoupons = Coupon::find($couponIDs);
return view('admin.coupons.print')->with(compact('selectedCoupons'));
}
现在我需要以某种方式遍历它们。
每 10 张优惠券我需要一个新的 "page" 块,因为 10 张优惠券适合一个页面块
每隔两张优惠券我需要一个新的 table 行,因为 2 张优惠券或 table 数据适合一行
有多种方法可以做到这一点,但我发现使用 Collection
对象的 chunk
方法非常可读。另一种选择是使用模数 ($index % 10 === 0
).
<div class="coupons">
{{-- Create chunks of 10 as this is the max per page --}}
@foreach($selectedCoupons->chunk(10) as $pageCoupons)
<div class="page">
<div class="subpage">
<table>
{{-- Create chunks of 2 so every row is filled with up to 2 coupons --}}
@foreach($pageCoupons->chunk(2) as $rowCoupons)
<tr>
{{-- Loop over the row coupons to create the columns --}}
@foreach($rowCoupons as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
@endforeach
</tr>
@endforeach
</table>
</div>
</div>
@endforeach
</div>
您可以使用集合的 chunk
方法来遍历您的优惠券块:
<div class="coupons">
@foreach ($selectedCoupons->chunk(10) as $page)
<div class="page">
<div class="subpage">
<table>
@foreach ($page->chunk(2) as $row)
<tr>
@foreach ($row as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
@endforeach
</tr>
@endforeach
</table>
</div>
</div>
@endforeach
</div>