将结果拆分为5列

时间:2016-06-28 04:07:00

标签: php laravel laravel-5 laravel-5.2

我有一个类似的查询:

$results = Post::all();

为简单起见,我们假设输出为此(id):

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

我的网站有5列布局。我需要将这些结果拆分/分成5列,这样结果如下:

 1 |  2 |  3 |  4 |  5
 6 |  7 |  8 |  9 | 10
11 | 12 | 13 | 14 | 15

5列布局像这样分割(列总数为25):

<div class="row">
    <div class="col-xs-5">
        //
    </div> 
    <div class="col-xs-5">
        //
    </div> 
    <div class="col-xs-5">
        //
    </div> 
    <div class="col-xs-5">
        //
    </div> 
    <div class="col-xs-5">
        //
    </div> 
</div>

如何像这样分割$results?有没有办法利用Laravel的Collection methods

2 个答案:

答案 0 :(得分:3)

试试这个,我认为应该给你预期的结果

$chunks = $results->chunk(5);
 dd($chunks->toarray());

Laravel文档

  

chunk方法将集合分成多个,更小的集合   给定大小的集合

它也可以像这样在视图中使用(在控制器中保持相同的查询并在视图中进行拆分)

修改

             @foreach ($results->chunk(5) as $chunk)
                 <div class="row">
                      @foreach ($chunk as $test)
                   <div class="col-md-2">
                     {{ $test->id }}
                   </div>
                      @endforeach
                 </div>
              @endforeach

<强>输出

enter image description here

答案 1 :(得分:0)

我认为@AchrafKhouadja是对的,您可以使用array_chunk()或Collection chunk(),这里有一个示例,说明如何将其呈现为您所期望的:

$cells = range(1, 25)
$rows  = array_chunk($cells, 5);

foreach ($rows as $row) {
    echo '<div class="row">';

    foreach ($row as $cell) {
        echo '<div class="col-xs-5">' . $cell . '</div>';
    }

    echo '</div>';
}

输出结果为:

<div class="row">
    <div class="col-xs-5">1</div>
    <div class="col-xs-5">2</div>
    <div class="col-xs-5">3</div>
    <div class="col-xs-5">4</div>
    <div class="col-xs-5">5</div>
</div>
<div class="row">
    <div class="col-xs-5">6</div>
    <div class="col-xs-5">7</div>
    <div class="col-xs-5">8</div>
    <div class="col-xs-5">9</div>
    <div class="col-xs-5">10</div>
</div>
<div class="row">
    <div class="col-xs-5">11</div>
    <div class="col-xs-5">12</div>
    <div class="col-xs-5">13</div>
    <div class="col-xs-5">14</div>
    <div class="col-xs-5">15</div>
</div>
<div class="row">
    <div class="col-xs-5">16</div>
    <div class="col-xs-5">17</div>
    <div class="col-xs-5">18</div>
    <div class="col-xs-5">19</div>
    <div class="col-xs-5">20</div>
</div>
<div class="row">
    <div class="col-xs-5">21</div>
    <div class="col-xs-5">22</div>
    <div class="col-xs-5">23</div>
    <div class="col-xs-5">24</div>
    <div class="col-xs-5">25</div>
</div>