Home > Enterprise >  laravel - formatting json array
laravel - formatting json array

Time:04-24

Currently, I am iterating a group of ids and fetching the members inside the group, and pushing it into a collection instance. I managed to push all the members, but the output that I want to get is not in the correct format. What I need to do is ensure that ID of 1,2 and 3 are on the same nested depth as ID 4. Any idea on how I can achieve this? Thank you.

Code Sample

$groupIds = [1,2,3];
        $colMembers = collect([]);

        foreach($groupIds as $groupId) {
            $groups = Group::find($groupId);
            $colMembers->push($groups->getStaffs);
        }

        $colMembers->push($requestorEmail);
        $colMembers->flatten();

        return $colMembers;

Output

[
   [
      {
         "id":1,
         "name":"User 1"
      }
   ],
   [
      {
         "id":2,
         "name":"User 2"
      }
   ],
   [
      {
         "id":3,
         "name":"User 3"
      }
   ],
   {
      "id":4,
      "name":"User 4"
   }
]

CodePudding user response:

maybe you would use this

pluck($array['colMembers'],'name','id');

note:

$array['the name of the external array']

hopefully that is help you

CodePudding user response:

I think it would be best here if you just merge the staff collection into the $colMembers, that way it won’t contain all the arrays.

  • Related