PHP数组在同一键上合并两个数组

我正在尝试将以下两个数组合并为一个共享相同密钥的数组:


第一个数组:


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

 }


猛跑小猪
浏览 482回答 3
3回答

阿晨1998

this would be one of the soluion:function array_merge_custom($array1,$array2) {&nbsp; &nbsp; $mergeArray = [];&nbsp; &nbsp; $array1Keys = array_keys($array1);&nbsp; &nbsp; $array2Keys = array_keys($array2);&nbsp; &nbsp; $keys = array_merge($array1Keys,$array2Keys);&nbsp; &nbsp; foreach($keys as $key) {&nbsp; &nbsp; &nbsp; &nbsp; $mergeArray[$key] = array_merge_recursive(isset($array1[$key])?$array1[$key]:[],isset($array2[$key])?$array2[$key]:[]);&nbsp; &nbsp; }&nbsp; &nbsp; return $mergeArray;}$array1 = array(&nbsp; &nbsp; array("Camera1" => "192.168.101.71"),&nbsp; &nbsp; array("Camera2" => "192.168.101.72"),&nbsp; &nbsp; array("Camera3" => "192.168.101.74"),);$array2 = array(&nbsp; &nbsp; array("Camera1" => "VT"),&nbsp; &nbsp; array("Camera2" => "UB"),&nbsp; &nbsp; array("Camera3" => "FX"));echo '<pre>';print_r(array_merge_custom($array1 , $array2));
打开App,查看更多内容
随时随地看视频慕课网APP