如何访问Laravel集合对象中的第n个对象?

编程入门 行业动态 更新时间:2024-10-20 07:49:34
本文介绍了如何访问Laravel集合对象中的第n个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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个对象?

本文发布于:2023-11-30 04:19:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:象中   对象   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!