Laravel分组集合返回对象而不是数组 [英] Laravel grouped collection returns object instead of array

查看:441
本文介绍了Laravel分组集合返回对象而不是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询

$outings = Outing::all()->groupBy(function ($item) {
   return Carbon::parse($item['start'])->format('m/d/Y');
});

return response()->json([
    'outings' => $outings
], 200);

响应返回一个对象,我需要它返回一个数组

The response is returning an object and I need it to return an array

如何使郊游成为数组而不是对象.

How can I get outings to be an array instead of an object.

如果我不对集合进行分组,而只是做

If I don't group the collection and just do

Outing::all();

它将返回一个数组而不是一个对象. Group by做的事情很奇怪.

It will return an array rather than an object. The Group by is doing something weird.

如果我DD($ outings)确实返回了一个集合,所以我认为将其返回到浏览器而不是数组时强制转换为对象是很奇怪的.

If I DD($outings) it does in fact return a collection, so I think it's odd that it gets cast to an object when returned to the browser rather than an array.

以下是我DD($ outings-> toArray())

Below is the output when I DD($outings->toArray())

谢谢

推荐答案

如果要数组,请使用此

If you want array then use this

$outings = Outing::all()->groupBy(function ($item) {
   return Carbon::parse($item['start'])->format('m/d/Y');
})->map(function($item){
    return $item->all();
});

return response()->json($outings, 200);

如果您希望日期作为键,那么

If you want date as key then

$outings = Outing::all()->groupBy(function ($item) {
   return Carbon::parse($item['start'])->format('m/d/Y');
});

return response()->json($outings->toArray(), 200);

这篇关于Laravel分组集合返回对象而不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆