使用php从两个数组中删除重复键

使用php从两个数组中删除重复键

问题描述:

I want to remove duplicate keys from both arrays.

My code is

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

$arr = array_diff($arr1, $arr2);

var_dump($arr); //It outputs null.

The final array should look like this--

$arr[22066] = array('ID' => 22066);
$arr[22067] = array('ID' => 22067);

Any help is highly appreciated.

我想从两个数组中删除重复的键。 p>

我的代码是 p>

  $ arr1 [22068] = array('ID'=> 22068); 
 $ arr1 [22067] = array('ID'=> 22067);  
 $ arr2 [22068] = array('ID'=> 22068); 
 $ arr2 [22066] = array('ID'=> 22066); 
 
 $ arr = array_diff($ arr1,  $ ARR2); 
 
var_dump($ ARR);  //它输出null。
  code>  pre> 
 
 

最终的数组应该如下所示 - p>

  $ arr [22066  ] = array('ID'=> 22066); 
 $ arr [22067] = array('ID'=> 22067); 
  code>  pre> 
 
 

任何 非常感谢帮助。 p> div>

array_diff_key() is what you want.

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

// Get elements of array 1 which are not present in array 2
$unique_1 = array_diff_key($arr1, $arr2);

// Get elements of array 2 which are not present in array 1
$unique_2 = array_diff_key($arr2, $arr1);

// Merge unique values
$unique = $unique_1 + $unique_2;

So array_diff will give you what's different in array1 vs array2, and will NOT work on multi-dimensional arrays. You can switch to array_key_diff, however, you'll run into a similar issue:

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

$arr = array_diff_key($arr1, $arr2);

var_dump($arr); //It outputs array(1) {[22067]=> array(1) { ["ID"]=> int(22067) } }

I'm not aware of a "magic" solution with the differences, however, you do have options, you can take the code above and add an extra line for:

$arr2 = array_diff_key($arr2, $arr1);
var_dump($arr2)

then merge $arr and $arr2, or you can just write a loop going through and comparing each item. Depending on size, scope, readability, etc will depend on the actual set