phparraysrecursionmultidimensional-arraymerging-data

Recursively merge two multidimensional associative arrays and define new subarray keys according to their origin array


I am trying to merge the following two arrays into one array, sharing the same key:

$array1 = [
    ["Camera1" => "192.168.101.71"],
    ["Camera2" => "192.168.101.72"],
    ["Camera3" => "192.168.101.74"],
];

$array2 = [
    ["Camera1" => "VT"],
    ["Camera2" => "UB"],
    ["Camera3" => "FX"]
];

As you can see, they share the same key (Camera1, Camera2, Camera3, etc..)

Here is what I have tried:

$Testvar = array_merge($NewArrayCam, $IpAddressArray);
foreach ($Testvar as $Newvals) {
    $cam = array();
    foreach ($Newvals as $K => $V) {
        $cam[] = array($K => $V);
    }
}

My desired result:

[
    'Camera1' => [
        'ip' => '192.168.101.71',
        'name' => 'VT',
    ],
    'Camera2' => [
        'ip' => '192.168.101.72',
        'name' => 'UB',
    ],
    'Camera3' => [
        'ip' => '192.168.101.74',
        'name' => 'FX',
    ]
]

Solution

  • 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)