我正在尝试将以下两个数组合并为一个共享相同密钥的数组:
第一个数组:
array(3) { [0]=> array(1) { ["Camera1"]=> string(14) "192.168.101.71" } [1]=> array(1) { ["Camera2"]=> string(14) "192.168.101.72" } [2]=> array(1) { ["Camera3"]=> string(14) "192.168.101.74" } }
第二个数组:
array(3) { [0]=> array(1) { ["Camera1"]=> string(2) "VT" } [1]=> array(1) { ["Camera2"]=> string(2) "UB" } [2]=> array(1) { ["Camera3"]=> string(2) "FX" } }
如您所见,它们共享相同的密钥(Camera1,Camera2,Camera3等。)
这是我尝试过的:
$Testvar = array_merge($NewArrayCam,$IpAddressArray); foreach ($Testvar AS $Newvals){ $cam = array(); foreach($Newvals AS $K => $V){ $cam[] = array($K => $V); }
理想情况下,我希望以一种方式格式化两个数组,array_merge_recursive从而简单地合并两个数组而不必大惊小怪。
array_merge_recursive
但是我确实提出了一个使用过的解决方案array_map。
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);
输出为:
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)