2015-02-23 110 views
2

我需要爲每個3個附件創建一行。類似於刀片模板佈局結構

@foreach($email->attachment as $attach) 
    <div class="row"> 
     <div class="col-lg-4"></div> 
     <div class="col-lg-4"></div> 
     <div class="col-lg-4"></div> 
    </div> 
@endforeach 

    <div class="row"> 
     <div class="col-lg-4">1st attachment</div> 
     <div class="col-lg-4">2nd attachment</div> 
     <div class="col-lg-4">3rd attachment</div> 
    </div> 
    <div class="row"> 
     <div class="col-lg-4">4th attachment</div> 
     <div class="col-lg-4">5th attachment</div> 
     <div class="col-lg-4">6th attachment</div> 
</div> 

等等!我曾搜索過這個問題,但發現了This link,但實際上與我的觀點不同。 感謝

回答

3

Use array_chunk - 它是專爲這每一個目的 - 讓您可以剪切一個數組子大小和循環通過每個組

@foreach (array_chunk($email->attachment->toArray(), 3, true) as $array) 
    <div class="row"> 
    @foreach($array as $attachment) 
     <div class="col-lg-4">{{ $attachment['id'] }}</div> 
    @endforeach 
    </div> 
@endforeach 

而且使用@ Lukasgeiter的評論 - 你也可以做到這這樣,如果它是一個Laravel Collection

@foreach ($email->attachment->chunk(3) as $array) 
    <div class="row"> 
    @foreach($array as $attachment) 
     <div class="col-lg-4">{{ $attachment->id }}</div> 
    @endforeach 
    </div> 
@endforeach 
+0

array_chunk需要一個數組而不是一個對象...... ?? – StraightForward 2015-02-23 07:38:32

+0

噢。首先轉換爲數組。看到我更新的答案。 – Laurence 2015-02-23 07:39:56

+3

假設'$ email-> attachment'是一個Laravel集合,您可以簡單地執行'$ email-> attachment-> chunk(3)' – lukasgeiter 2015-02-23 07:45:01

0

試試這個,它的速度比生成2個數組:

<div class="row"> 
    @foreach($email->attachment as $index => $attach) 
     <div class="col-lg-4">{{$attach}}</div> 
     @if($index+1 === 0) 
     </div><div class="row"> 
     @endif 
    @endforeach 
    </div>