简体   繁体   中英

break row from foreach loop

I am trying to break foreach loop.

 @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$. My problem is loop.I am unable to break listing of data in foreach. Please help me if any suitable away where I can calculate data by similller ID.

You have to reshape your data so it contains price against the respective id . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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