How to access the nth item in a Laravel collection?

烂漫一生 提交于 2019-11-30 23:15:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!