我想我故意提出一个重复的问题是违反了所有规则...

The other question has an accepted answer. It obviously solved the askers problem, but it did not answer the title question.

Let's start from the beginning - the first() method is implemented approximately like this:

foreach ($collection as $item)
    return $item;

这显然比取$collection[0]或使用其他建议的方法更稳健.

即使集合中有20个项,也可能没有索引为015的项.为了说明这个问题,让我们从文档中删除以下集合:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'desk'],
    ['product_id' => 'prod-200', 'name' => 'chair'],
]);

$keyed = $collection->keyBy('product_id');

现在,我们有没有可靠(最好是简洁)的方法来访问第n个$keyed项?

My own suggestion would be to do:

$nth = $keyed->take($n)->last();

但是,无论何时$n > $keyed->count(),这都会给出错误的项目($keyed->last()).如果第n项存在,我们怎么能得到它,如果它不像first()那样表现,我们怎么能得到它呢?

编辑

为了澄清,让我们来考虑一下这个集合:

$col = collect([
    2 => 'a',
    5 => 'b',
    6 => 'c',
    7 => 'd']);

第一项是$col->first().如何获得第二个?

$col->nth(3)应该返回'c'(如果基于0,则返回'c',但这与first()不一致).$col[3]不起作用,它只会返回一个错误.

$col->nth(7)应该返回null,因为没有第七项,只有四项.$col[7]不起作用,它只会返回'd'.

You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.

推荐答案

我想更快、更节省内存的方法是使用slice()方法:

$collection->slice($n, 1);

Laravel相关问答推荐

保存很多模型太慢

为什么在Blade 文件中输出用户通知时出现错误?

发送邮箱后,Laravel重定向偶尔会导致错误500

Laravel中的策略对我不起作用,这是我的代码

Laravel 语法 GroupBy 获取列到数组

如何使用动态翻译键翻译 Laravel硬编码字符串(还有 1 个错误)..(验证异常类)

将数据从控制器传递到 Laravel 中的视图

Laravel + Plupload 上传到 S3 响应以进行预检无效 - CORS

查询 Laravel Select WhereIn 数组

允许的内存大小 134217728 字节用尽(试图分配 20480 字节) Laravel

Laravel transformer vs resource

如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

Laravel - 排序的集合输出不是数组

laravel 中的 Http Post 使用 fetch api 给出 TokenMismatchException

CRON 作业(job) - LARAVEL - 输出

在 Laravel 中,如何获取 *only* POST 参数?

Laravel Socialite 在本地主机上进行测试,SSL 证书问题?

配置和测试 Laravel 任务调度

laravel - 无法在控制器构造函数中获取会话

连接到 tcp://smtp.mail.yahoo.com:465 超时