引用 Laravel 集合中的下一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35114081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reference next item in a Laravel collection
提问by samiles
I am looping through a Laravel collection sorted by created_at
to make a timeline. The start date for each item is created_at
, and the end date is the created_at
of the following item. If it is the last item, the event just lasts for a set 30 days.
我正在循环浏览按排序的 Laravel 集合created_at
以制作时间线。每个项目的开始日期是created_at
,结束日期是created_at
以下项目的 。如果是最后一个项目,则该事件仅持续 30 天。
My current code is this:
我目前的代码是这样的:
@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
As you can see here the end date is just the same as the start date, but I need it to be the start date of the next item. I thought there would be a helper like last()
for collections that I could just call next()
or whatever. As there's no numeric key, I can't just add one and grab it. The item are sorted by date, and the only ID type field is the one from the database which is a random ID like 1434 or 1356.
正如您在此处看到的,结束日期与开始日期相同,但我需要将其作为下一项的开始日期。我以为会有一个像last()
我可以打电话next()
或其他任何东西的收藏品的帮手。由于没有数字键,我不能加一个就可以抓取。该项目按日期排序,唯一的 ID 类型字段是数据库中的一个,它是一个随机 ID,如 1434 或 1356。
Any ideas on how to get the next item's start_date, and check if we are at the last item? I looked at PHP's next
function but I don't think it does what I need.
关于如何获取下一项的 start_date 并检查我们是否在最后一项的任何想法?我查看了 PHP 的next
函数,但我认为它不能满足我的需求。
Many thanks
非常感谢
回答by shrimpwagon
You have to get the Iterator first:
你必须先得到迭代器:
$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);
回答by Mike Miller
The collection will be keyed by an incrementing index so you should be able to do...
该集合将以递增索引为键,因此您应该能够执行...
$collection = $statushistory->where('itemid', $timelineitemid);
foreach ($collection->values() as $index=>$hist){
//stuff here
$next =$collection->get(++$index) ;
}
Blade syntax obviously a bit different but hopefully illustrate the idea
Blade 语法显然有点不同,但希望能说明这个想法