简体   繁体   English

从 foreach 循环中断行

[英]break row from foreach loop

I am trying to break foreach loop.我正在尝试打破 foreach 循环。

 @foreach($referralData->product as $data)
<tr>
<td>{{$data->id}}</td>
<td>{{$data->price}}</td>
</tr>
@endforeach

Out put of this loop is这个循环的输出是

id 7
price 30$
id 7
price 80$



 id 8
    price 90$
    id 8 
   price 80$

What I am trying to do calculate total of id, something like Id 7=110$ and Id=8= 170$.我正在尝试计算 id 的总数,例如 Id 7=110$ 和 Id=8=170$。 My problem is loop.I am unable to break listing of data in foreach.我的问题是循环。我无法打破 foreach 中的数据列表。 Please help me if any suitable away where I can calculate data by similller ID.如果有合适的地方我可以通过 similller ID 计算数据,请帮助我。

You have to reshape your data so it contains price against the respective id .您必须重塑您的数据,使其包含针对相应idprice You can do this before the loop:您可以在循环之前执行此操作:

$result = collect($referralData->product)->groupBy('id')->map(function ($item) {
            return $item->sum('price');
        });

After that, in your loop, do the following:之后,在您的循环中,执行以下操作:

@foreach($result as $id => $price)
<tr>
<td>{{$id}}</td>
<td>{{$price}}</td>
</tr>
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM