php laravel 集合到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35284974/
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
laravel collection to array
提问by datavoredan
I have two models, Post
and Comment
; many comments belong to a single post. I'm trying to access all comments associated with a post as an array.
我有两个模型,Post
并且Comment
;许多评论属于一个帖子。我正在尝试以数组的形式访问与帖子相关的所有评论。
I have the following, which gives a collection.
我有以下内容,提供了一个集合。
$comments_collection = $post->comments()->get()
$comments_collection = $post->comments()->get()
How would I turn this $comments_collection
into an array? Is there a more direct way of accessing this array through eloquent relationships?
我如何把它$comments_collection
变成一个数组?有没有更直接的方式通过雄辩的关系访问这个数组?
回答by Drudge Rajen
You can use toArray()of eloquent as below.
您可以使用eloquent 的toArray()如下。
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 模型,模型也将被转换为数组
$comments_collection = $post->comments()->get()->toArray()
From Laravel Docs:
来自 Laravel 文档:
toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the allmethod instead.
toArray 还将作为 Arrayable 实例的所有集合嵌套对象转换为数组。如果要获取原始底层数组,请改用all方法。
回答by paranoid
Try this:
尝试这个:
$comments_collection = $post->comments()->get()->toArray();
see this can help you
toArray() method in Collections
看到这可以帮助你
在集合中的 toArray() 方法
回答by eithed
Use all()
method - it's designed to return items of Collection:
使用all()
方法 - 它旨在返回集合项目:
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
回答by Akshay Kulkarni
you can do something like this
你可以做这样的事情
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
Reference is https://laravel.com/docs/5.1/collections#method-toarray
参考是https://laravel.com/docs/5.1/collections#method-toarray
Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
最初来自 Laracasts 网站https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
回答by TechPotter
Use collect($comments_collection)
.
使用collect($comments_collection)
.
Else, try json_encode($comments_collection)
to convert to json.
否则,尝试json_encode($comments_collection)
转换为 json。
回答by Ferhat KO?ER
Try collectfunction in array like:
尝试在数组中收集函数,例如:
$comments_collection = collect($post->comments()->get()->toArray());
this methods can help you
这些方法可以帮助你
toArray()with collect()
toArray()和collect()