Home > OS >  Grouping a collection IN LARAVEL
Grouping a collection IN LARAVEL

Time:10-15

I have an array called $customerRecords. I want to group the data in this array by the customer's email.

This is the array below

$customerRecords = [
    {
        "id": 1,
        "note": "This is note 1",
        "customer": [
            {
                "id": 1,
                "user_id": 34,
                "email": "[email protected]",
                "phone": "9829484857"
            }
        ]
    },
    {
        "id": 2,
        "note": "This is note 2",
        "customer": [
            {
                "id": 2,
                "user_id": 34,
                "email": "[email protected]",
                "phone": "9829484857"
            }
        ]
    },
    {
        "id": 3,
        "note": "This is a note 3",
        "customer": [
            {
                "id": 2,
                "user_id": 34,
                "email": "[email protected]",
                "phone": "9829484857"
            }
        ]
    },
]

This is the expected result I want to achieve so that I can know the group of data that belongs to an email .

    {
        "[email protected]": [
            {
                "id": 1,
                "note": "This is note 1",
                "customer": [
                    {
                        "id": 1,
                        "user_id": 34,
                        "email": "[email protected]",
                        "phone": "9829484857"
                    }
                ]
            }
        ],
        "[email protected]": [
            {
                "id": 2,
                "note": "This is note 2",
                "customer": [
                    {
                        "id": 2,
                        "user_id": 34,
                        "email": "[email protected]",
                        "phone": "9829484857"
                    }
                ]
            },
            {
                "id": 3,
                "note": "This is a note 3",
                "customer": [
                    {
                        "id": 2,
                        "user_id": 34,
                        "email": "[email protected]",
                        "phone": "9829484857"
                    }
                ]
            }
        ]
    }

So this is what I have tried but it's not working:

return collect($customerRecords)->groupBy('customer.email')

CodePudding user response:

you are almost done just define customer 0 item then email

  return collect($customerRecords)->groupBy('customer.0.email');

CodePudding user response:

This is how I was able to solve it.

$grouped = [];
foreach($customerRecords as $value) {
    foreach($value['customer'] as $cust) {
        $grouped[$cust['email']][] = $value;
    }
}
  • Related