如何访问Laravel集合对象中的第n个对象? [英] How to access the nth object in a Laravel collection object?
问题描述
我有一个laravel收集对象.
I have a laravel collection object.
我想在其中使用第n个模型.
I want to use the nth model within it.
我如何访问它?
在 laravel文档中找不到合适的方法.我可以在foreach循环中迭代集合,并在找到第n个项目时中断:
I cannot find a suitable method in the laravel documentation. I could iterate the collection in a foreach loop and break when the nth item is found:
foreach($collection as $key => $object)
{
if($key == $nth) {break;}
}
// $object is now the nth one
但这似乎很混乱.
一种更简洁的方法是执行一次以上循环,并创建一个包含集合中所有对象的简单数组.但这似乎是不必要的重复.
A cleaner way would be to perform the above loop once and create a simple array containing all the objects in the collection. But this seems like unnecessary duplication.
在 laravel集合类文档中,有一个访存方法,但我认为这将从匹配主键的集合中获取一个对象,而不是集合中的第n个对象.
In the laravel collection class documentation, there is a fetch method but I think this fetches an object from the collection matching a primary key, rather than the nth one in the collection.
推荐答案
看到Illuminate\Support\Collection
实现了ArrayAccess
,您应该能够简单地使用方括号表示法,即
Seeing as Illuminate\Support\Collection
implements ArrayAccess
, you should be able to simply use square-bracket notation, ie
$collection[$nth]
这会在内部调用offsetGet
,您也可以使用
This calls offsetGet
internally which you can also use
$collection->offsetGet($nth)
最后,您可以使用get
方法,该方法允许使用可选的默认值
and finally, you can use the get
method which allows for an optional default value
$collection->get($nth)
// or
$collection->get($nth, 'some default value')
这篇关于如何访问Laravel集合对象中的第n个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!