-3

I have two simple arrays structured like the (simplified) example below. I simply want to merge them into one 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
  )
) 
user229044
  • 232,980
  • 40
  • 330
  • 338
Jay
  • 151
  • 1
  • 13
  • 3
    ***This question does not show any research effort**; it is unclear or not useful* is probably why people have downvoted your question. Although you may have done some research, there is no evidence in the question itself. – Nigel Ren Oct 29 '20 at 07:55
  • @NigelRen i do try everything but could not get desire result , so at the end i post it here. – Jay Oct 29 '20 at 08:00
  • 1
    Does this answer your question? [Merging two arrays by index](https://stackoverflow.com/questions/9541598/merging-two-arrays-by-index) – digijay Oct 29 '20 at 08:02
  • @digijay , no , that is different. – Jay Oct 29 '20 at 08:05
  • 1
    @Jay that's not different, you just not trying it. – Alive to die - Anant Oct 29 '20 at 08:18
  • @Jay how you are getting `[paid] => 24809` in your desired output for `[user_id] => 5`, while array1 have no data available for `[user_id] => 5`? – Alive to die - Anant Oct 29 '20 at 10:07

1 Answers1

1

Quite easy solution:

$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;
}

Output of merge($arr1, $arr2) is:

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

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

)
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sunfline
  • 139
  • 2
  • 8