递归array_diff()? [英] recursive array_diff()?

查看:23
本文介绍了递归array_diff()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些工具来为我提供两个数组的递归差异.我设想的是一个带有两种颜色编码树结构的网页.在每棵树上,绿色是数组中在两个数组中都匹配的部分,红色是每个数组中不匹配的部分.类似于dbug的输出

I'm looking for some tool to give me a recursive diff of two arrays. What I envision is a web page with two color-coded tree-structures. On each tree, green are parts of the array which match in both arrays, and red is for parts of each that don't match the other. Something like the output of dBug

我有一些代码可以为我提供一个嵌套数组来填充报告.我正在开发一种应该更快的新方法,但我需要测试值和结构,以确保它提供与旧方法相同的输出.

I have some code that gives me a nested array to populate a report. I'm developing a new method that should be faster, but I need to test the values and also the structure, to make sure it gives output identical to the old method.

有什么可以使用的吗?还是我需要写这个?或者还有其他方法可以实现我的目标吗?

Is there something out there that I can use? Or do I need to write this? Or is there another way to accomplish my goals?

推荐答案

array_diff.

function arrayRecursiveDiff($aArray1, $aArray2) {
  $aReturn = array();

  foreach ($aArray1 as $mKey => $mValue) {
    if (array_key_exists($mKey, $aArray2)) {
      if (is_array($mValue)) {
        $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
        if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
      } else {
        if ($mValue != $aArray2[$mKey]) {
          $aReturn[$mKey] = $mValue;
        }
      }
    } else {
      $aReturn[$mKey] = $mValue;
    }
  }
  return $aReturn;
} 

该实现一次只处理两个数组,但我认为这并没有真正的问题.如果您一次需要 3 个或更多数组的差异,您可以按顺序运行差异.此外,此方法使用密钥检查并进行松散验证.

The implementation only handles two arrays at a time, but I do not think that really posses a problem. You could run the diff sequentially if you need the diff of 3 or more arrays at a time. Also this method uses key checks and does a loose verification.

这篇关于递归array_diff()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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