Search code examples
phparraysobjectmultidimensional-arrayarray-merge

Push elements from a flat array into an object array by related index


I have two arrays like below:

array 1:

array([0]=> 11, [1] => 2.5)

array 2:

Array ( 
    [0] => stdClass Object ( 
        [type] => 1 
        [creator_id] => 3 
        [creator_name] => E1 
        [per_tar] => 300 
        [pro_tar] => 200 
        [ac] => 300 
        [PA] => 17 
        [Q1] => 800 
    ) 
    [1] => stdClass Object ( 
        [type] => 1 
        [creator_id] => 4 
        [creator_name] => E2 
        [per_tar] => 100 
        [pro_tar] => 170 
        [ac] => 0 
        [PA] => 7 
        [Q1] => 270 
    ) 
) 

I want is to merge the first array with the second array with the following logic:

Array 1 key [0] is merged inside array 2 key [0] object, and so on in the same fashion for all keys.

So my expected output is:

Array ( 
    [0] => stdClass Object ( 
        [type] => 1 
        [creator_id] => 3 
        [creator_name] => E1 
        [per_tar] => 300 
        [pro_tar] => 200 
        [ac] => 300 
        [PA] => 17 
        [Q1] => 800
        [new] => 11 
    ) 
    [1] => stdClass Object ( 
        [type] => 1 
        [creator_id] => 4 
        [creator_name] => E2 
        [per_tar] => 100 
        [pro_tar] => 170 
        [ac] => 0 
        [PA] => 7 
        [Q1] => 270
        [new] => 2.5 
    ) 
) 

I am trying the array_merge() function, but it's incorrectly merging both arrays into a four-element array.


Solution

  • $res = [];
    foreach($array1 as $key => $val){
        // before merging convert object to array
        $arr = is_object($array2[$key]) ? (array)$array2[$key] : $array2[$key];  
        $res[$key] = array_merge($array1[$key], $arr);
    }
    
    print_r($res);