问题
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.
Let's start from the beginning - the first()
method is implemented approximately like this:
foreach ($collection as $item)
return $item;
It is obviously more robust than taking $collection[0]
or using other suggested methods.
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');
Now, do we have any reliable (and preferably concise) way to access nth item of $keyed
?
My own suggestion would be to do:
$nth = $keyed->take($n)->last();
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?
Edit
To clarify, let's consider this collection:
$col = collect([
2 => 'a',
5 => 'b',
6 => 'c',
7 => 'd']);
First item is $col->first()
. How to get the second?
$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)
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'
.
You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.
回答1:
I guess faster and more memory-efficient way is to use slice() method:
$collection->slice($n, 1);
回答2:
You can try it using values() function as:
$collection->values()->get($n);
回答3:
Based on Alexey's answer, you can create a macro in AppServiceProvider (add it inside register method):
use Illuminate\Support\Collection;
Collection::macro('getNth', function ($n) {
return $this->slice($n, 1)->first();
});
and then, you can use this throughout your application:
$collection = ['apple', 'orange'];
$collection->getNth(0) // returns 'apple'
$collection->getNth(1) // returns 'orange'
$collection->getNth(2) // returns null
$collection->getNth(3) // returns null
回答4:
Maybe not the best option, but, you can get item from array inside collection
$collection->all()[0]
来源:https://stackoverflow.com/questions/40444759/how-to-access-the-nth-item-in-a-laravel-collection