Thursday, 30 August 2018

PHP Adding multiple associative arrays to a new array based on the key

I have a few associative arrays that I need to merge together based on there key. so:

array1:
 [person1] => tony
 [person2] => sandra 

array2:
 [person1] => london
 [person2] => paris

needs to be :
 array 3
  [person1] => tony , london
  [person2] => sandra , paris

The issue I'm having though is that the key could be any value , so it could be 'person1' or it could be 'hairyOtter' and the array is of varaible size.

Assuming, that every is not multi-dimensional
$merged = array_merge_recursive($array1, $array2);
foreach ($merged as &$entry) {
  if (is_array($entry)) {
    $entry = implode(', ', $entry);
  }
}

The idea is, that array_merge_recursive() creates a new array, if it find two values with the same key. Everything else stays untouched.

0 comments:

Post a Comment