PHP Array Merge two Arrays on same key

Solution 1:

Ideally I would look to format the two arrays in such a way that array_merge_recursive would simply merge the arrays without too much fuss.

However I did come up with a solution that used array_map.

$array1 = array(
    array("Camera1" => "192.168.101.71"),
    array("Camera2" => "192.168.101.72"),
    array("Camera3" => "192.168.101.74"),
);

$array2 = array(
    array("Camera1" => "VT"),
    array("Camera2" => "UB"),
    array("Camera3" => "FX")
);

$results = array();

array_map(function($a, $b) use (&$results) {

    $key = current(array_keys($a));
    $a[$key] = array('ip' => $a[$key]);

    // Obtain the key again as the second array may have a different key.
    $key = current(array_keys($b));
    $b[$key] = array('name' => $b[$key]);

    $results += array_merge_recursive($a, $b);

}, $array1, $array2);

var_dump($results);

The output is:

array (size=3)
  'Camera1' => 
    array (size=2)
      'ip' => string '192.168.101.71' (length=14)
      'name' => string 'VT' (length=2)
  'Camera2' => 
    array (size=2)
      'ip' => string '192.168.101.72' (length=14)
      'name' => string 'UB' (length=2)
  'Camera3' => 
    array (size=2)
      'ip' => string '192.168.101.74' (length=14)
      'name' => string 'FX' (length=2)

Solution 2:

Try to use array_merge_recursive.

Solution 3:

Use array_merge_recursive :

Convert all numeric key to strings, (make is associative array)

$result = array_merge_recursive($ar1, $ar2);
print_r($result);

Ref : http://php.net/array_merge_recursive