如何从PHP中的最后一个元素开始迭代foreach循环?

时间:2020-06-18 09:18:23

标签: php laravel

我有一个通过代码从laravel中的数据库中获取的结果集。

$products = Product::whereNull('box_size')->get();

$ products变量中大约有18000个对象。我需要从列表中获取最后一个对象的前一个对象。我该怎么办?有什么方法可以从结果集的最后一个遍历一个foreach循环吗?

4 个答案:

答案 0 :(得分:1)

如果只需要一条记录,请在查询中更精确地避免大量额外的数据加载和处理:

$products = Product::whereNull('box_size')
                   ->orderBy('created_at', 'DESC')
                   ->skip(1)
                   ->take(1)
                   ->get();

答案 1 :(得分:0)

您可以轻松地从模型中完成此操作(对于最后10个查询):

$products = Product::orderBy('id', DESC)->whereNull('box_size')->take(10)->get();

仅用于最后一个查询:

$products = Product::orderBy('id', DESC)->whereNull('box_size')->first();

或者,使用foreach循环仅获得10个结果:

@php
    $i= 0;
@endphp

@foreach($all as $data) {
   $i++;
   include $data->name;
   if($i == 10) break;
 }
@endforeach

答案 2 :(得分:0)

上面提到的您可以通过模型来做到:

$products = Product::latest()->whereNull('box_size')->get();

这将使您雄辩地使用DESC在created_at列中排序的所有产品。

答案 3 :(得分:0)

  1. 您可以按降序对结果进行排序,然后第二项就是您想要的:
$products = Product::orderBy('id', DESC)->whereNull('box_size')->get();
$item = $products[1];
  1. 直接从Collection对象访问该项目:
$products = Product::whereNull('box_size')->get();

$item = $products->get($products->count() - 2);

//or pop
$products->pop()
$item = $products->pop();
相关问题