Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group a 2d array by one column andform subarrays within each group using another column


I have an array that looks like the following:

$myArray = 
[
  ['email' => 'email1@email.com', 'value' => '123'],
  ['email' => 'email1@email.com', 'value' => '456'],
  ['email' => 'email1@email.com', 'value' => '789'],
  ['email' => 'email2@email2.com', 'value' => '123'],
  ['email' => 'email2@email2.com', 'value' => '456'],
  ...
]

What is a good way to combine the values according to unique column values (email) such that the previous array would end up like so:

[
  'email@email.com' => ['123', '456'],
  'email2@email2.com' => ['123', '456', '789'],
  ...
]

I can think of solutions, but they all seem quite inefficient :( Here is one for example:

$resultArray = array();
foreach ($myArray as $info) {
    if (!isset($resultArray[$info['email']])) {
        $resultArray[$info['email']] = array();
    }
    array_push($resultArray[$info['email']], $info['value']);
}

This doesn't sit well with me for some reason.

QUESTION

Are there better solutions?

-- Updated my Blatant Mistake - Check new (1st) array :/ --


Solution

  • All your checks and uses of array_push() can be replaced by the empty array indexer. This greatly simplifies your loop as follows:

    foreach ($myArray as $item) {
        $result[$item['email']][] = $item['value'];
    }
    

    An example of this is here.