参考Laravel集合中的下一个项目

时间:2016-01-31 12:55:44

标签: php laravel laravel-collection

我循环浏览按created_at排序的Laravel集合来制作时间轴。每个项目的开始日期为created_at,结束日期为以下项目的created_at。如果它是最后一项,则该事件将持续30天。

我目前的代码是:

@foreach ($statushistory->where('itemid', $timelineitemid) as $hist)
    [ '{{$hist->newstatus}}', new Date({{$hist->created_at->format('Y')}}, {{$hist->created_at->format('n')-1}}, {{$hist->created_at->format('j')}}), new Date({{$hist->created_at->format('Y')}}, {{$hist->created_at->format('n')-1}}, {{$hist->created_at->format('j')}}) ],
@endforeach

正如您在此处所看到的结束日期与开始日期相同,但我需要它作为下一个项目的开始日期。我认为会有一个像last()这样的帮助器,我可以称之为next()或其他任何东西。由于没有数字键,我无法添加一个并抓住它。该项目按日期排序,唯一的ID类型字段是数据库中的字段,它是随机ID,如1434或1356.

有关如何获取下一个项目的start_date的任何想法,并检查我们是否在最后一项?我查看了PHP的next函数,但我认为它不能满足我的需求。

非常感谢

2 个答案:

答案 0 :(得分:5)

你必须先得到Iterator:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);

答案 1 :(得分:2)

该集合将通过递增索引进行键控,因此您应该可以执行...

$collection = $statushistory->where('itemid', $timelineitemid);

foreach ($collection->values() as $index=>$hist){
      //stuff here
      $next =$collection->get(++$index) ;  
 } 

刀片语法显然有点不同,但希望能够说明这个想法

相关问题