Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

PHP Array Merge two Arrays on same key

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

First Array:

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"
}
}

Second Array:

array(3) {
 [0]=>
  array(1) {
  ["Camera1"]=>
  string(2) "VT"
 }
 [1]=>
 array(1) {
   ["Camera2"]=>
   string(2) "UB"
 }
 [2]=>
 array(1) {
  ["Camera3"]=>
  string(2) "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);
 }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...