Not able to group inner array of the multi-dimensional array

Viewed 14

I have an array like this & I need to group an array based on value.

array:3 [
  0 => array:5 [
    "id" => 1
    "maxView" => 0
    "maxClick" => 20
    "companyName" => "Project A"
    "email" => "user1@email.com"
  ]
  1 => array:5 [
    "id" => 1
    "maxView" => 0
    "maxClick" => 20
    "companyName" => "Project A"
    "email" => "user2@email.com"
  ]
  2 => array:5 [
    "id" => 1
    "maxView" => 0
    "maxClick" => 20
    "companyName" => "Project A"
    "email" => "user3@email.com"
  ]
  3 => array:5 [
    "id" => 1
    "maxView" => 0
    "maxClick" => 20
    "companyName" => "Project B"
    "email" => "user1@email.com"
  ]
  4 => array:5 [
    "id" => 1
    "maxView" => 0
    "maxClick" => 20
    "companyName" => "Project B"
    "email" => "user6@email.com"
  ]
]

So far, I have following lines of codes. This is grouping my array based on fieldName = companyName But I am not able to add emails belonging to companyname under an array.

foreach ($records as $record) {
    if (!array_key_exists($record[$fieldName], $groupedArray)) {
        $groupedArray[$record[$fieldName]] = [];
    }
    $groupedArray[$record[$fieldName]] = $record;
    $groupedArray[$record[$fieldName]]['email'] = [];

    if (!in_array($record['email'], $groupedArray[$record[$fieldName]]['email'], true)) {
    $groupedArray[$record[$fieldName]]['email'][] = $record['email'];
    }
}

My code is adding only last email to the array. "Project A" => [ .... "email" => array:1 [ 0 => "user3@email.com" ]

Can anybody help me what I am missing here ?

0 Answers
Related