PHP:在两个多维数组之间获得差异

时间:2015-02-11 09:54:38

标签: php arrays multidimensional-array

我有两个数组,比如

$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,并且还分开了函数,但是我无法做出正确的事情。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

快速解决方案,未优化

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