skip to Main Content

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')

2

Answers


  1. Chosen as BEST ANSWER

    This is how I was able to solve it.

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

  2. you are almost done just define customer 0 item then email

      return collect($customerRecords)->groupBy('customer.0.email');
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search