【问题标题】:Output Laravel collection in groups of two以两组输出 Laravel 集合
【发布时间】:2017-08-13 01:02:21
【问题描述】:

我正在努力将 Laravel 刀片中的表格分成两列。例如,如果我有 17 行,我想在第一列中显示其中的 9 行,在第二列中显示其余的。这是我的代码:

@foreach($idAndProducts as $id)
<tr>
<td width="15px">
<input type="checkbox" id="products{{$id->product_id}}" name="products[]" value="{{$id->product_id}}">
<input type="hidden" name="campaignID[]" value="{{$id->id}}"></td>
<td width="480px"><label for="products{{$id->product_id}}">{{$id->products}}</label></td>
</tr>
@endforeach

有没有办法在 Blade 中或使用 jQuery 做到这一点?

【问题讨论】:

    标签: php jquery laravel laravel-blade


    【解决方案1】:

    您可以使用array_chunk 将它们分成两组。试试这个:

    @foreach ( array_chunk($idAndProducts, 2) as $row )
        <tr>
        @foreach ( $row as $id )
            <td width="15px">
                <input type="checkbox" id="products{{$id->product_id}}" name="products[]" value="{{$id->product_id}}">
                <input type="hidden" name="campaignID[]" value="{{$id->id}}">         
            </td>
            <td width="480px">
                <label for="products{{$id->product_id}}">{{$id->products}}</label>
            </td>
        @endforeach
        </tr>
    @endforeach
    

    请注意,如果$idAndProductscollection,那么array_chunk 将不起作用。您将需要改用内置方法chunk。只需更新第一行即可阅读

    @foreach ( $idAndProducts->chunk(2) as $row )
    

    【讨论】:

    • 我刚刚更新了我的答案。我不确定$idAndProducts 是否是一个集合。
    • 对不起。我刚刚看到您的编辑并删除了我关于收集错误的评论。现在它完美地工作了。谢谢!
    • 这正是我所需要的。谢谢!
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多