Laravel php combine two foreach

2019-08-30 00:00发布

In my blade.php file, I'm trying to merge two foreach loop to display data in the table. I had tried use something like nested loop but it doesn't work.

@foreach($cat->products as $idx => $product)
    <tr ng-init="item.items[{{$cat->id}}][{{$idx}}] = {};">
    @foreach ($queryInv as $querInvs)
        <td>{{$product->sku}}</td>
        <td>{{$product->name}}</td>
        <td class="text-right">{{{$querInvs->total or 0}}}</td>
    </tr>
    @endforeach
@endforeach

I just need to insert the total data into the table. Now the total is displayed correctly but it will duplicate the sku and name in the table.

1条回答
劫难
2楼-- · 2019-08-30 00:30

Define an array which we will use as a "flag" and on each iteration check if the current product SKU is NOT in our "flag" array. If it isn't then we display and we add the current product SKU to the list of processed SKUs and continue as normal.

@php $skus = [] @endphp
@foreach($cat->products as $idx => $product)
    @if (!in_array($product->sku, $skus))
        <tr ng-init="item.items[{{$cat->id}}][{{$idx}}] = {};">
            @foreach ($queryInv as $querInvs)
                <td>{{$product->sku}}</td>
                <td>{{$product->name}}</td>
                <td class="text-right">{{{$querInvs->total or 0}}}</td>
            @endforeach
        </tr>
        @php array_push($skus, $product->sku); @endphp
    @endif
@endforeach

Note: You are using Laravel 4, the current version of Laravel is 5.7, I would absolutely update and use the latest version.

Reading Material

in_array

array_push

查看更多
登录 后发表回答