本文介绍了PHP:获得两个多维数组之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组

$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,也尝试了单独的功能,但是我无法正确地进行操作。 / p>

I have tried array_udiff, and also separate function but I'm unable to get the right thing.

推荐答案

Hmm快速解决方案,未优化

Hmm fast solution, not optimized

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

编辑:略有优化(取消了之前找到的值):

A little optimized (unseting values that were found before):

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

这篇关于PHP:获得两个多维数组之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:13