Laravel如何将集合和数组合并到json并将它们分开

时间:2019-02-11 20:42:06

标签: arrays laravel collections

我有两种类型的集合和数组,我想正确地合并。 我希望使用weekSummary(0-6)和LatestUsers(7-9)来代替1,2,3,4,5,6,7,8,9。我使用array_merge合并集合和数组。

$panelData = array_merge($weekSummary, $latestUsers->toArray(), ['total_users' => User::count()]);

是否可以像使用变量一样用JSON分隔它们?

{
"0": {
"day": "2019-02-05",
"users_count": 2
},
"1": {
"day": "2019-02-06",
"users_count": 4
},
"2": {
"day": "2019-02-07",
"users_count": 7
},
"3": {
"day": "2019-02-08",
"users_count": 2
},
"4": {
"day": "2019-02-09",
"users_count": 5
},
"5": {
"day": "2019-02-10",
"users_count": 0
},
"6": {
"day": "2019-02-11",
"users_count": 1
},
"7": {
 user 1 data ...
},
"8": {
 user 2 data ...
},
"9": {
 users 3 data ...
},
"total_users": 567
}

我想要JSON:

   {
    "weekSummary": [
    {
     "day": "2019-02-05",
     "users_count": 2
    },
    ...],
    "latestUsers": [
    {
     user 1 data ...
    },
    ...],
    "total_users": 567
   }

1 个答案:

答案 0 :(得分:0)

它应该很简单(不合并它们):

$panelData = [
  'weekSummary' => $weekSummary,
  'latestUsers' => $latestUsers->toArray(),
  'total_users' => User::count()
];

//result

json_encode($panelData);