How to access the nth object in a Laravel collection object?

只愿长相守 提交于 2019-11-30 17:11:28

Seeing as Illuminate\Support\Collection implements ArrayAccess, you should be able to simply use square-bracket notation, ie

$collection[$nth]

This calls offsetGet internally which you can also use

$collection->offsetGet($nth)

and finally, you can use the get method which allows for an optional default value

$collection->get($nth)
// or
$collection->get($nth, 'some default value')

@Phil's answer doesn't quite obtain the nth element, since the keys may be unordered. If you've got an eloquent collection from a db query it'll work fine, but if your keys aren't sequential then you'll need to do something different.

$collection = collect([0 => 'bish', 2 => 'bash']); $collection[1] // Undefined index

Instead we can do $collection->values()[1] // string(4) bash which uses array_values()

Or even make a macro to do this:

Collection::macro('nthElement', function($offset, $default = null) {
    return $this->values()->get($offset, $default);
}):

Example macro usage:

$collection = collect([0 => 'bish', 2 => 'bash']);
$collection->nthElement(1) // string(4) 'bash'
$collection->nthElement(3) // undefined index
$collection->nthElement(3, 'bosh') // string (4) bosh

If you are having problems with the collection keeping the indices after sorting... you can make a new collection out of the values of that collection and try accessing the newly indexed collection like you would expect:

e.g. Get the second highest priced item in a collection

$items = collect(
                 [
                  "1" => ["name" => "baseball", "price" => 5],
                  "2" => ["name"=> "bat", "price" => 15],
                  "3" => ["name" => "glove", "price" => 10]
                 ]
                );

collect($items->sortByDesc("price")->values())[1]["name"];

// Result: glove

Similar to morphs answer but not the same. Simply using values() after a sort will not give you the expected results because the indices remain coupled to each item.

Credit to @howtomakeaturn for this solution on the Laravel Github: https://github.com/laravel/framework/issues/1335

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