Search code examples
phparraysarray-merge

PHP append elements from another associative array into same array with same keys


I have a few associative arrays and I would like to combine them into one associative array. For example:

$array_1 = Array 
( 
    [0] => Array ( [user_id] => 111 [first_name] => Jack [last_name] => Scotts [email] )
    [1] => Array ( [user_id] => 222 [first_name] => David [last_name] => Weathers [email] )
    [2] => Array ( [user_id] => 333 [first_name] => Helen [last_name] => Reynolds [email] )
)

$array_2 = Array 
( 
    [111] => Array 
    ( 
        [0] => Array([user_account] => 111_001 [account_type] => normal ) 
        [1] => Array([user_account] => 111_002 [account_type] => vip )
    )

    [222] => Array 
    ( 
        [0]=> Array([user_account] => 222_01 [account_type] => normal ) 
    )
    [333] => Array 
    ( 
        [0]=> Array([user_account] => 333_01[account_type] => vip )
    )
)


Results:
$new_array = Array 
( 
    [0] => Array 
    ( 
        [user_id] => 111 
        [first_name] => Jack 
        [last_name] => Scotts 
        [account_data] = > Array 
        ( 
            [0] => Array([user_account] => 111_001 [account_type] => normal ) 
            [1] => Array([user_account] => 111_002 [account_type] => vip )
         )
    )
    [1] => Array 
    ( 
        [user_id] => 222 
        [first_name] => David 
        [last_name] => Weathers
        [account_data] => Array 
        ( 
            [0]=> Array([user_account] => 222_01 [account_type] => normal ) 
        )
     )
    [2] => Array 
    ( 
        [user_id] => 333 
        [first_name] => Helen 
        [last_name] => Reynolds 
        [account_data] => Array
        (
            [0] => Array ( [user_account] => 333_01 [account_type] => vip )
        )
    )
)

Tried both array_merge and array_merge recursive but it doesn't work.


Solution

  • There is no native PHP functionality for this, since this is not a very standard way of merging arrays together. You can write a loop that will do it for you though, using foreach():

    $new_array = [];
    
    foreach($array_1 as $user){
        $temp = $user;
        $temp['account_data'] = $array_2[$user['user_id']];
        $new_array[] = $temp;
    }
    

    Demo