如何访问Laravel集合中的第n个项目? [英] How to access the nth item in a Laravel collection?
问题描述
我想我是通过故意重复一个问题来打破所有规则的...
I guess I am breaking all the rules by deliberately making a duplicate question...
其他问题有一个可接受的答案.它显然解决了提问者问题,但没有回答标题问题.
The other question has an accepted answer. It obviously solved the askers problem, but it did not answer the title question.
让我们从头开始-first()
方法的实现大致如下:
Let's start from the beginning - the first()
method is implemented approximately like this:
foreach ($collection as $item)
return $item;
它显然比采用$collection[0]
或使用其他建议的方法更强大.
It is obviously more robust than taking $collection[0]
or using other suggested methods.
即使集合中有20个项目,也可能没有索引为0
或索引为15
的项目.为了说明问题,让我们从文档中取出这个集合:
There might be no item with index 0
or index 15
even if there are 20 items in the collection. To illustrate the problem, let's take this collection out of the docs:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'desk'],
['product_id' => 'prod-200', 'name' => 'chair'],
]);
$keyed = $collection->keyBy('product_id');
现在,我们是否有任何可靠的(最好是简洁的)方法来访问$keyed
的第n个项目?
Now, do we have any reliable (and preferably concise) way to access nth item of $keyed
?
我个人的建议是:
$nth = $keyed->take($n)->last();
但是,每当$n > $keyed->count()
时,这将给出错误的项目($keyed->last()
). 如果第n个项存在,而又不像first()
那样,我们怎么得到null
?
But this will give the wrong item ($keyed->last()
) whenever $n > $keyed->count()
. How can we get the nth item if it exists and null
if it doesn't just like first()
behaves?
为澄清起见,让我们考虑以下集合:
To clarify, let's consider this collection:
$col = collect([
2 => 'a',
5 => 'b',
6 => 'c',
7 => 'd']);
第一个项目是$col->first()
.如何获得第二个?
First item is $col->first()
. How to get the second?
$col->nth(3)
应该返回'c'
(如果从0开始,则返回'c'
,但这与first()
不一致). $col[3]
不起作用,它只会返回一个错误.
$col->nth(3)
should return 'c'
(or 'c'
if 0-based, but that would be inconsistent with first()
). $col[3]
wouldn't work, it would just return an error.
$col->nth(7)
应该返回null
,因为没有第七项,只有四个. $col[7]
不起作用,它只会返回'd'
.
$col->nth(7)
should return null
because there is no seventh item, there are only four of them. $col[7]
wouldn't work, it would just return 'd'
.
您可以将问题改写为如何以foreach顺序获得第n个项目?"如果对某些人更清楚.
You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.
推荐答案
我想更快,更节省内存的方法是使用 slice()
方法:
I guess faster and more memory-efficient way is to use slice()
method:
$collection->slice($n, 1);
这篇关于如何访问Laravel集合中的第n个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!