Search code examples
phparrayslaravelcollections

Laravel how to merge collections and arrays to json and separate them


I have 2 types collection and array i would like to merge correcly. Instead of 1,2,3,4,5,6,7,8,9 i would like to have weekSummary(0-6) and latestUsers(7-9). I use array_merge to merge collection and array.

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

Is it possible to separate them in JSON as they are in variables?

{
"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
}

i would like to have JSON:

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

Solution

  • It should be simple as this (without merging them):

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