PHP: 获取两个多维数组之间的差异

PHP: Getting difference between two multidimensional arrays

我有两个数组

$a1= array(
      array('a'=>1,'b'=>2, 'c'=>3), // similar to $a2[0]
      array('a'=>3,'b'=>4, 'c'=>5), // similar to $a2[1]
      array('a'=>9,'b'=>6, 'c'=>9)
);
$a2= array(
      array('a'=>1,'b'=>2, 'c'=>3),
      array('a'=>3,'b'=>4, 'c'=>5),
      array('a'=>5,'b'=>6, 'c'=>7),
      array('a'=>11,'b'=>4, 'c'=>13),
      array('a'=>14,'b'=>6, 'c'=>3)
);

我想要一个没有像

这样的公共值的结果数组
  $arrayResult= array(
      array('a'=>9,'b'=>6, 'c'=>9),// from $a1[3]
      array('a'=>5,'b'=>6, 'c'=>7),// from $a2[2]
      array('a'=>11,'b'=>4, 'c'=>13),// from $a2[3]
      array('a'=>14,'b'=>6, 'c'=>3)// from $a2[4]
);

我试过array_udiff,也试过单独的函数,但我无法得到正确的东西。

function check_diff_multi($array1, $array2){
    $result = array();
    foreach($array1 as $key => $val) {
        if(isset($array2[$key])){
           if(is_array($val)  && is_array($array2[$key])){
                $result[$key] = check_diff_multi($val, $array2[$key]);
            }
        } else {
            $result[$key] = $val;
        }
    }

    return $result;
} 

//call this function  
check_diff_multi($a1,$a2);

嗯快速解决方案,未优化

$result = array();
foreach($a1 as $va1) {
   $found = false;
   foreach($a2 as $va2) {
      $x = array_diff($va1, $va2);
      if (empty($x)) {
         $found = true;
      }
   }
   if (!$found) { 
      $result[] = $va1;
   }
}

foreach($a2 as $va2) {
   $found = false;
   foreach($a1 as $va1) {
      $x = array_diff($va2, $va1);
      if (empty($x)) {
         $found = true;
      }
   }
   if (!$found) { 
      $result[] = $va2;
   }
}

var_dump($result);

编辑:稍微优化(取消之前发现的值):

$a1= array(
      array('a'=>1,'b'=>2, 'c'=>3), // similar to $a2[0]
      array('a'=>3,'b'=>4, 'c'=>5), // similar to $a2[1]
      array('a'=>9,'b'=>6, 'c'=>9)
);
$a2= array(
      array('a'=>1,'b'=>2, 'c'=>3),
      array('a'=>3,'b'=>4, 'c'=>5),
      array('a'=>5,'b'=>6, 'c'=>7),
      array('a'=>11,'b'=>4, 'c'=>13),
      array('a'=>14,'b'=>6, 'c'=>3)
);
$i=0;
$result = array();
    foreach($a1 as $ka1 => $va1) {
       $found = false;
       foreach($a2 as $ka2 => $va2) {
          $i++;
          $x = array_diff($va1, $va2);
          if (empty($x)) {
             $found = true;
             unset($a2[$ka2], $a1[$ka1]);
          }
       }
       if (!$found) { 
          $result[] = $va1;
       }
    }
    foreach($a2 as $ka2 => $va2) {
   $found = false;
   foreach($a1 as $ka1 => $va1) {
      $i++;
      $x = array_diff($va2, $va1);
      if (empty($x)) {
         unset($a2[$ka2], $a1[$ka1]);
         $found = true;
      }
   }
   if (!$found) { 
      $result[] = $va2;
   }
}

var_dump($result);echo $i;