Search code examples
phparraysmultidimensional-arrayduplicatesarray-merge

Combining two or more arrays into one array according to numeric keys without duplicates in subarrays


I have the following scenario made of arrays with numeric keys. I need to have an array which stores all the values in the arrays grouped by numeric key and without duplicates. I cannot make them strings as they are IDs and need to stay numeric.

Starting point:

    Array
    (
        [77] => Array
            (
                [0] => Bold Condensed
                [1] => Bold Condensed 2
                [2] => Bold Condensed 3
            )
    
    )
    Array
    (
        [77] => Array
            (
                [0] => Bold Condensed
            )
    
        [136] => Array
            (
                [0] => Regular
            )
    
    )
    Array
    (
        [77] => Array
            (
                [0] => Bold Condensed (1, 2, 3)
            )
    
        [168] => Array
            (
                [0] => Regular
                [1] => Bold
            )
    
    )

Expected output:

Array
(
    [77] => Array
        (
            [0] => Bold Condensed
            [1] => Bold Condensed 2
            [2] => Bold Condensed 3
            [3] => Bold Condensed (1 ,2 ,3)
        )

    [136] => Array
        (
            [0] => Regular
        )

    [168] => Array
        (
            [0] => Regular
            [1] => Bold
        )

)

Tried array_merge and array_merge_recursive:

$megaArray = [];

foreach( $arrays as $key => $value) {
  if(array_key_exists($key, $arrays)){
    $megaArray[$key] = array_merge_recursive($value);
  }
}

What I'm getting with both array_merge and array_merge_recursive:

Array
(
    [77] => Array
        (
            [0] => Bold Condensed (1, 2, 3)
        )

    [136] => Array
        (
            [0] => Regular
        )

    [168] => Array
        (
            [0] => Regular
            [1] => Bold
        )

)

Both array_merge() and array_merge_recursive() seem to store the latest value for each key.


Solution

  • I think you just need a combination of array_merge and array_unique (since I note you don't have duplicates in your leaf arrays):

    $megaArray = [];
    
    foreach ($arrays as $subArray) {
      foreach ($subArray as $key => $value) {
        if (array_key_exists($key, $megaArray)) {
          $megaArray[$key] = array_unique(array_merge($megaArray[$key], $value));
        } else {
          $megaArray[$key] = $value;
        }
      }
    }