编辑;我知道这个问题根据标题得到了很多点击,所以这些人的 TLDR 是使用collect()
帮助器创建 Collection 实例。回答提问者的简介:
如果你有
$collection = collect([
(object) [
'website' => 'twitter',
'url' => 'twitter.com'
],
(object) [
'website' => 'google',
'url' => 'google.com'
]
]);
然后将数组包装在 Collection 类的实例中。
这意味着它的行为不像典型的数组(-它将是类似数组的,但不要将它视为一个数组-),直到您调用all()
or toArray()
在上面。要删除您需要使用的任何添加的索引values()
.
$sorted = $collection->sortBy('website');
$sorted->values()->all();
预期输出:
[
{#769
+"website": "google",
+"url": "google.com",
},
{#762
+"website": "twitter",
+"url": "twitter.com",
},
]
请参阅文档https://laravel.com/docs/5.1/collections#available-methods https://laravel.com/docs/5.1/collections#available-methods
The toArray
方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,则模型也会转换为数组。
The all
方法返回由集合表示的基础数组。