在 Laravel 中将数组转换为集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49083535/
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
Convert Array To Collection in Laravel
提问by user3718908
I have the following array in PHP:
我在 PHP 中有以下数组:
[
{
"website": "example",
"url": "example.com"
},
{
"website": "example",
"url": "example.com"
}
]
Now I would like to convert this to a collection so I sort by the keys website
or url
. However when I do this:
现在我想将其转换为集合,因此我按键website
或url
. 但是,当我这样做时:
$myArray = collect(websites);
I get this instead:
我得到了这个:
{
"0": {
"website": "example",
"url": "example.com"
},
"1": {
"website": "example",
"url": "example.com"
}
}
And the sorting does not work, I would like to know what I am doing wrong and how I can fix it so I have an array collection of objects I can easily sort.
并且排序不起作用,我想知道我做错了什么以及如何修复它,以便我有一个可以轻松排序的对象数组集合。
Edit:I expect the output to be the same as this:
编辑:我希望输出与此相同:
[
{
"website": "example",
"url": "example.com"
},
{
"website": "example",
"url": "example.com"
}
]
By "sorting does not work" I meant the items are not sorted.
“排序不起作用”是指项目没有排序。
回答by Jonathan
If you have
如果你有
$collection = collect([
(object) [
'website' => 'twitter',
'url' => 'twitter.com'
],
(object) [
'website' => 'google',
'url' => 'google.com'
]
]);
You then have your array wrapped in an instance of the Collection class.
That means it does not behave like a typical array (- it will be array-like, but don't treat it like it is one -) until you call all()
or toArray()
on it. To remove any added indices you need to use values()
.
然后,您将数组包装在 Collection 类的实例中。这意味着它的行为不像典型的数组( - 它会像数组一样,但不要把它当作一个 - ),直到你调用all()
或toArray()
在它上面。要删除任何添加的索引,您需要使用values()
.
$sorted = $collection->sortBy('website');
$sorted->values()->all();
The expected output:
预期输出:
[
{#769
+"website": "google",
+"url": "google.com",
},
{#762
+"website": "twitter",
+"url": "twitter.com",
},
]
See the docs https://laravel.com/docs/5.1/collections#available-methods
请参阅文档https://laravel.com/docs/5.1/collections#available-methods
The toArray
method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays.
该toArray
方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,模型也将被转换为数组。
The all
method returns the underlying array represented by the collection.
该all
方法返回由集合表示的底层数组。
回答by AbdulBasit
In my case I was making an collection to fake a service for test purpose so I use
在我的情况下,我正在制作一个集合来伪造服务以用于测试目的,所以我使用
$collection = new Collection();
foreach($items as $item){
$collection->push((object)['prod_id' => '99',
'desc'=>'xyz',
'price'=>'99',
'discount'=>'7.35',
]);
}