我想我故意提出一个重复的问题是违反了所有规则...
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个项,也可能没有索引为0
或15
的项.为了说明这个问题,让我们从文档中删除以下集合:
$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.