按索引或组合数组合并两个数组?

Merging two arrays by index or combine array?

我有两个简单的数组,其结构类似于下面的(简化)示例。我只是想将它们合并成一个数组。

$array1 :

Array ( 
  [0] => Array ( 
    [user_id] => 65
    [paid] => 24809
  )  
  [1] => Array ( 
    [user_id] => 54
    [paid] => 3574      
  )
) 

$array2 :

Array (
 [0] => Array (
    [user_id] => 54
    [unpaid] => 42277
)  
 [1] => Array (
   [user_id] => 65
   [unpaid] => 3860
)
 [2] => Array (
   [user_id] => 5
  [unpaid] => 3860
 )
) 

$desiredResult :

Array (
 [0] => Array (
    [user_id] => 54
    [paid] => 3574  
    [unpaid] => 42277
)  
 [1] => Array (
   [user_id] => 65
   [paid] => 24809
   [unpaid] => 3860
)
 [2] => Array (
   [user_id] => 5
   [paid] => 24809
   [unpaid] => 3860
  )
) 

非常简单的解决方案:

$arr1 = Array (
    Array (
        'user_id' => 65,
        'paid' => 24809
    ),
    Array (
        'user_id' => 54,
        'paid' => 3574
    )
);

$arr2 = Array (
    Array (
        'user_id' => 54,
        'unpaid' => 42277
    ),
    Array (
        'user_id' => 65,
        'unpaid' => 3860
    ),
    Array (
        'user_id' => 5,
        'unpaid' => 3860
    )
);

/**
 * @param array<mixed> $arr1
 * @param array<mixed> $arr2
 * @return array<mixed>
 */
function merge(array $arr1, array $arr2): array
{
    $result = [];
    foreach ($arr1 as $key => $value) {
        $result[$key] = array_merge($value, $arr2[$key]);
    }
    return $result;
}

merge($arr1, $arr2) 的输出是:

Array
(
    [0] => Array
        (
            [user_id] => 54
            [paid] => 24809
            [unpaid] => 42277
        )

    [1] => Array
        (
            [user_id] => 65
            [paid] => 3574
            [unpaid] => 3860
        )

)