Laravel雄辩toArray不使用方括号 [英] Laravel Eloquent toArray not using square braces
问题描述
[
{
id:0,...
},
{
id:,...
},
]
而是,Laravel使用表格键将其显示为键值,值列表:
0:{
{
id:0
}
},
1:{
{
id:1,...
}
这是功能:
$ results = \App\Event :: with('sandboxes') - > get() - > sortBy('start_time') - > ; forPage($页次,$ perPage);
return response() - > json(array(
events=> $ page,
));
如何让Laravel给我一个正确的数组?
当您第一次获得您的活动时,您的集合
看起来像这样:
[
0 => Event1,
1 => Event2,
2 => Event3
]
这是一个正确索引的数字数组,可以表示为数组在JSON中。但是,一旦您收到 Collection
,您就可以在 sortBy()
中调用 C $ C>集合
。此排序重新排列数组中的项和项的值。此时,您的集合
可能如下所示:
[
1 => Event2,
0 => Event1,
2 => Event3
]
这不是一个正确索引的数字数组,不能表示为JSON中的数组。这个数组必须被表示为一个对象,这是你看到的。
为了获得你期待的结果,你需要重新键入项在集合
中排序后。您可以在 Collection
(即调用 array_values)中的
。 values()
方法()
一旦你重新加密了你的收藏,它将看起来像:
[
0 => Event2,
1 => Event1,
2 =>事件3
]
这是一个正确索引的数字数组,可以表示为一个数组在JSON中。
所以,你的代码应该如下所示:
$ results = \App\Event :: with('sandboxes')
- > get()
- > sortBy('start_time')
- > values )//对
- > forPage($ pageNum,$ perPage)进行排序后,重新键入集合中的项目;
I'm writing an api and attempting to convert a number of results into JSON. When the eloquent result is converted to an array, I am expecting something like this:
[
{
"id": "0", ...
},
{
"id": "", ...
},
]
but instead, Laravel displays it as a key, value list using the table key:
"0":{
{
"id": "0", ...
}
},
"1":{
{
"id": "1", ...
}
}
Here is the function:
$results = \App\Event::with('sandboxes')->get()->sortBy('start_time')->forPage($pageNum,$perPage);
return response()->json(array(
"events" => $page,
));
How can I get Laravel to give me a proper array?
When you first get your events, your Collection
looks something like this:
[
0 => Event1,
1 => Event2,
2 => Event3
]
This is a properly indexed numeric array, and can be represented as an array in JSON. However, once you get your Collection
, you call sortBy()
on it, which sorts the items in the Collection
. This sorting rearranges both the keys and the values of the items inside the array. At this point, your Collection
may look something like:
[
1 => Event2,
0 => Event1,
2 => Event3
]
This is not a properly indexed numeric array, and cannot be represented as an array in JSON. This array must be represented as an object, which is what you are seeing.
In order to get the results you're expecting, you need to re-key the items in the Collection
after you sort it. You can do this with the values()
method on the Collection
(which just calls array_values()
on the internal items array).
Once you re-key your Collection, it will look something like:
[
0 => Event2,
1 => Event1,
2 => Event3
]
This is now a properly indexed numeric array and can be represented as an array in JSON.
So, your code should look something like:
$results = \App\Event::with('sandboxes')
->get()
->sortBy('start_time')
->values() // re-key the items in the collection after sorting
->forPage($pageNum, $perPage);
这篇关于Laravel雄辩toArray不使用方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!