Search code examples
phparraysarray-merge

Merge arrays containing shared associative keys without overwriting each other


I am working with multiple APIs returning data as flat arrays. All of these APIs are returning arrays with shared keys.

For example:

Returning data from API A,B and C:

$a = array(1 => "abc", 2 => "def");
$b = array(1 => "ghi", 2 => "jkl");
$c = array(1 => "mno", 2 => "pqr");

All of these arrays have repeated numeric keys. My requirement is a single array without losing values due to key collisions.

Required outcome:

array(
    "abc",
    "def",
    "ghi",
    "jkl",
    "mno",
    "pqr"
);

I tried array_merge() function but it overwrites the duplicated key and array_merge_recursive() function accumulate all repeated key into another array.


Solution

  • Try this.......

    $a=array(1=>"abc",2=>"def");
    $b=array(1=>"ghi",2=>"jkl");
    $c=array(1=>"mno",2=>"pqr");
    
    $d = array();
    
    foreach($a as $arr){
     array_push($d, $arr);
    }
    
    foreach($b as $arr){
     array_push($d, $arr);
    }
    
    foreach($c as $arr){
     array_push($d, $arr);
    }
    print_r($d);
    

    Output is

    Array ( [0] => abc [1] => def [2] => ghi [3] => jkl [4] => mno [5] => pqr )
    

    I also tried your example with array merge & it gave me following o/p.

    Array ( [0] => abc [1] => def [2] => ghi [3] => jkl [4] => mno [5] => pqr )