PHP - Mutidimensional阵列差异 [英] PHP - Mutidimensional array diff

查看:143
本文介绍了PHP - Mutidimensional阵列差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问您的帮助,因为我有困难解决这个问题。我已经创建了一个功能,方便对数组差异但并不足够我的需要。感谢和更多的权力!

i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!

<?php
   $arraySession = array(
      'sampleA' => array('1', '2', '3'),
      'sampleB' => array('1', '2', '3'),
   );

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1','2'),
);

结果应该是:

array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)

我现有的功能:

    public function array_diff_multidimensional($session, $post) { 
      $result = array();
      foreach($session as $sKey => $sValue){
          foreach($post as $pKey => $pValue) {
              if((string) $sKey == (string) $pKey) {
                  $result[$sKey] = array_diff($sValue, $pValue);
              } else {
                  $result[$sKey] = $sValue;
              }
          }
      }
      return $result;
    }

任何帮助将是非常美联社preciated!编码快乐!

Any help would be much appreciated! Happy coding!

推荐答案

不是我的功能,而不是由我测试过,但是这是第一次意见逐一php.net/array_diff(归功于在Gmail的点com到thefrox)

Not my function and not tested by me, but this was one of the first comments at php.net/array_diff (credit goes to thefrox at gmail dot com)

<?php
function multidimensional_array_diff($a1, $a2) {
    $r = array();

    foreach ($a2 as $key => $second) {
        foreach ($a1 as $key => $first) {
          if (isset($a2[$key])) {
              foreach ($first as $first_value) {
                  foreach ($second as $second_value) {
                      if ($first_value == $second_value) {
                          $true = true;
                          break;
                      }
                  }
                  if (!isset($true)) {
                      $r[$key][] = $first_value;
                  }
                  unset($true);
              }
          } else {
              $r[$key] = $first;
          }
        }
    }
    return $r;
}
?>

这篇关于PHP - Mutidimensional阵列差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆