0

Having these two arrays with exactly the same number of items (3) and respectively correspondent data, how can I merge them to one unique array, combining the data like I show in array 3 example

// array 1
[ ▼ 3 items
  {
    "email": "[email protected]"
  },
  {
    "email": "[email protected]"
  },
  {
    "email": "[email protected]"
  }
]

// array 2
[ ▼ 3 items
  {
    "name": "John Doe"
  },
  {
    "name": "Joe Bloggs"
  },
  {
    "name": "Foo Bar"
  }
]

How can I merge them to be like this:

// array 3
[ ▼ 3 items
  {
    "name": "John Doe",
    "email": "[email protected]"
  },
  {
    "name": "Joe Bloggs",
    "email": "[email protected]"
  },
  {
    "name": "Foo Bar",
    "email": "[email protected]"
  }
]

I am using laravel php. I have tried array_merge($array1, $array2) and some laravel's function $res = $array1->merge($array2); but I can't get the result I want.

hailton
  • 591
  • 1
  • 3
  • 15
  • Can you provide a `var_dump()` of the arrays? I'm not really sure what that output is that you're giving. – Patrick Q Oct 01 '18 at 21:20

3 Answers3

3

array_merge doesn't combines the elements, it just concatenates the arrays to each other.

You can use array_map() to call array_merge() on each pair of elements:

$result = array_map('array_merge', $array1, $array2);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Use combine() method of laravel

$collection = collect(['name', 'email']);
for($i=0;$i<count($array1);$i++){
$combined[] = $collection->combine([$array2[$i],$array1[$i]]);
}
$combined->all();

or just use collection

$collection = collect($array1, $array2);
Osama
  • 2,912
  • 1
  • 12
  • 15
1

I don't know how your input data looks like so I had to make a few assumptions. The idea is to loop through all emails, take their position in the emails array, and use that position to define what the name would be in the names array.

$emails = [
    ["email" => "[email protected]"], 
    ["email" => "[email protected]"], 
    ["email" => "[email protected]"]
];

$names = [
    ["name" => "John Doe"],
    ["name" => "Joe Bloggs"],
    ["name" => "Foo Bar"]
];

$names_and_emails = [];

foreach ($emails as $key => $email) {
    $names_and_emails[] = ["email" => $email['email'], "name" => $names[$key]['name']];
}

var_dump($names_and_emails);

Output:

array(3) {
  [0]=>
  array(2) {
    ["email"]=>
    string(20) "[email protected]"
    ["name"]=>
    string(8) "John Doe"
  }
  [1]=>
  array(2) {
    ["email"]=>
    string(22) "[email protected]"
    ["name"]=>
    string(10) "Joe Bloggs"
  }
  [2]=>
  array(2) {
    ["email"]=>
    string(19) "[email protected]"
    ["name"]=>
    string(7) "Foo Bar"
  }
}

Hope this helps.

mkveksas
  • 171
  • 8
  • 1
    @hailton thanks for accepting my answer! This is also a good example to understand what's going on behind the scenes when using the array_merge() or Laravel combine() methods. – mkveksas Oct 02 '18 at 07:56