Search code examples
phpentity-attribute-value

Combining multiple associative arrays efficiently on an ID key


I have a bunch of php arrays that look like this (please don't ask why, I'm just doing my job...All I will say is EAV...):

$firstNames = ([accountId] => 100, [firstName] => 'John'
               [accountId] => 101, [firstName] => 'Fred');


$lastNames =  ([accountId] => 100, [lastName] => 'Doe'
               [accountId] => 101, [lastName] => 'Bloggs');


$city      =  ([accountId] => 100, [city] => 'New York'
               [accountId] => 101, [city] => 'Cambridge');


$country   =  ([accountId] => 100, [country] => 'USA'
               [accountId] => 101, [country] => 'UK');

etc etc.

I have to combine them into one array:

$userDetails =  ([accountId] => 100, [firstName] => "John", [lastName] => "Doe", 
                 [city] => "New York", [country] => "USA");

My feeling is the correct answer would be to break these attributes out of EAV and model them correctly. But I can't. It would also be possible to do self-join upon self-join in the db, but I have simplified the example and this is not really possible - and I've been told to do it this way...There could be a bunch of additional fields tacked on as well, later.

So what is the best way to produce one associative array, merging on accountId in PHP? Is there a function, or do I need to loop round and round etc.


Solution

  • This nested foreach should do it:

    $result = array();
    
    foreach (array('firstNames' => 'firstName', 'lastNames' => 'lastName', 'city' => 'city', 'country' => 'country') as $srcArr => $arrKey) {
      foreach ($$srcArr as $item) {
        if (!isset($result[$item['accountId']])) {
          $result[$item['accountId']] = $item;
        } else {
          $result[$item['accountId']][$arrKey] = $item[$arrKey];
        }
      }
    }
    
    var_dump($result);
    

    See it working