为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
猛跑小猪 2019-11-19 11:08:42
我正在尝试将以下两个数组合并为一个共享相同密钥的数组:第一个数组: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); }
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

this would be one of the soluion:


function array_merge_custom($array1,$array2) {

    $mergeArray = [];

    $array1Keys = array_keys($array1);

    $array2Keys = array_keys($array2);

    $keys = array_merge($array1Keys,$array2Keys);


    foreach($keys as $key) {

        $mergeArray[$key] = array_merge_recursive(isset($array1[$key])?$array1[$key]:[],isset($array2[$key])?$array2[$key]:[]);

    }


    return $mergeArray;


}


$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")

);

echo '<pre>';

print_r(array_merge_custom($array1 , $array2));


查看完整回答
反对 回复 2019-11-19
  • 3 回答
  • 0 关注
  • 481 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信