Laravel php combine two foreach

我与影子孤独终老i 提交于 2019-12-25 01:05:10

问题


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:


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



来源:https://stackoverflow.com/questions/53496854/laravel-php-combine-two-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!