如何进行迭代,然后在 Blade PHP (Laravel) 中断后再次迭代同一对象

How can I make an iteration then iterate the same object again after a break in Blade PHP (Laravel)

在我的控制器中,我传递了一个 Collection 的 8 项:

$data['items'] = Item::orderBy('id','desc')->take(8)->get();

查看。使用 Blade,我想将集合分成两半并在不同位置渲染每一半:

@foreach($items as $item)
  // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items as $item)
  // iterate the rest 4 items from the same object $items
@endforeach

我该怎么做?

See the Chunk() method:

The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

This method is especially useful in views when working with a grid system such as Bootstrap. Imagine you have a collection of Eloquent models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

根据您的具体情况,您可以这样做:

@foreach($items->chunk(4)->toArray[1] as $item)
  //iterate "n" times (4 for example)
@endforeach

some <html>

@foreach($items->chunk(4)->toArray[2] as $item)
  //iterate the rest 4 items from the same object $items
@endforeach

Slice 你的 $items collection 对半:

// Slice collection from the 0 index for a length of 4 (the first 4 items)
@foreach($items->slice(0, 4) as $item)
  // ...
@endforeach

// Iterate over the rest from th 4 index. 
// By passing the second parameter you can restrain the length.
@foreach($items->slice(4) as $item)
  // ...
@endforeach

或者chunk把它分成两个collection。

您可以使用 split method 将 collection 分成给定数量的组:

示例:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8]);

$groups = $collection->split(2);

$groups->toArray(); // [[1, 2, 3, 4], [5, 6, 7, 8]]

在你的控制器中:

$data['items'] = Item::orderBy('id','desc')->take(8)->get()->split(2);

Blade:

@foreach($items[0] as $item)
    // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items[1] as $item)
    // iterate the rest 4 items from the same object $items
@endforeach