如何访问 Laravel 集合对象中的第 n 个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24443949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the nth object in a Laravel collection object?
提问by theHands
I have a laravel collection object.
我有一个 Laravel 集合对象。
I want to use the nth model within it.
我想在其中使用第 n 个模型。
How do I access it?
我如何访问它?
Edit:
编辑:
I cannot find a suitable method in the laravel documentation. I could iterate the collection in a foreach loop and break when the nth item is found:
我在laravel 文档中找不到合适的方法。我可以在 foreach 循环中迭代集合并在找到第 n 个项目时中断:
foreach($collection as $key => $object)
{
if($key == $nth) {break;}
}
// $object is now the nth one
But this seems messy.
但这似乎很混乱。
A cleaner way would be to perform the above loop once and create a simple array containing all the objects in the collection. But this seems like unnecessary duplication.
更简洁的方法是执行上述循环一次并创建一个包含集合中所有对象的简单数组。但这似乎是不必要的重复。
In the laravel collection class documentation, there is a fetch method but I think this fetches an object from the collection matching a primary key, rather than the nth one in the collection.
在laravel 集合类文档中,有一个 fetch 方法,但我认为这会从与主键匹配的集合中获取一个对象,而不是集合中的第 n 个对象。
回答by Phil
Seeing as Illuminate\Support\Collection
implements ArrayAccess
, you should be able to simply use square-bracket notation, ie
看到Illuminate\Support\Collection
实现ArrayAccess
,你应该能够简单地使用方括号表示法,即
$collection[$nth]
This calls offsetGet
internally which you can also use
这在offsetGet
内部调用,您也可以使用
$collection->offsetGet($nth)
and finally, you can use the get
method which allows for an optional default value
最后,您可以使用get
允许可选默认值的方法
$collection->get($nth)
// or
$collection->get($nth, 'some default value')
回答by Harry
@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.
@Phil 的答案并没有完全获得第 n 个元素,因为键可能是无序的。如果您从 db 查询中获得了 eloquent 集合,它会正常工作,但如果您的键不是连续的,那么您需要做一些不同的事情。
$collection = collect([0 => 'bish', 2 => 'bash']); $collection[1] // Undefined index
$collection = collect([0 => 'bish', 2 => 'bash']); $collection[1] // Undefined index
Instead we can do $collection->values()[1] // string(4) bash
which uses array_values()
相反,我们可以做$collection->values()[1] // string(4) bash
which 使用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
回答by Noah Gary
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.
类似于 morphs 答案但不一样。简单地values()
在排序后使用不会给你预期的结果,因为索引仍然与每个项目耦合。
Credit to @howtomakeaturn for this solution on the Laravel Github: https://github.com/laravel/framework/issues/1335
在 Laravel Github 上将此解决方案归功于 @howtomakeaturn:https: //github.com/laravel/framework/issues/1335