-1

What is the best way to merge two arrays which contain sub arrays? Is there an function to do this and is it possible to do that without using loop? I have tried using function array_merge_recursive, but it's not doing what I need.

These are example arrays:

array1 = [
  [0] => [person] => [
    'name' => 'John'
  ],
  [1] => [person] => [
    'name' => 'Arya'
  ]
]

array2 = [
  [0] => [person] => [
    'surname' => 'Snow'
  ],
  [1] => [person] => [
    'surname' => 'Stark'
  ]
]

What I need:

array3 = [
  [0] => [person] => [
    'name' => 'John'
    'surname' => 'Snow'
  ],
  [1] => [person] => [
    'name' => 'Arya'
    'surname' => 'Stark'
  ]
]

But with above mentioned function I am getting array with 4 elements, two names and two surnames.

niksrb
  • 459
  • 7
  • 25

1 Answers1

1

Use array_map with array_merge:

$array3 = array_map('array_merge', $array1, $array2);

array_map calls a function on the corresponding elements of each of the input arrays. Then array_merge combines those sub-arrays.

Barmar
  • 741,623
  • 53
  • 500
  • 612