PHP通过键和值比较两个多维数组 [英] PHP Compare two multidimensional arrays by key and value

查看:356
本文介绍了PHP通过键和值比较两个多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于学习PHP,并且正在寻找一种通过键和值来比较两个关联数组的方法,然后找出两者的差值,即

I am busy learning PHP and was looking for a way to compare two associative arrays by both key and value and then find the difference of the two i.e.

如果我有一个关联数组:

If I had an associative array with:

array (size=2)
  'x15z' => int '12' (length=2)
  'x16z' => int '3' (length=1)

另一个带有以下内容:

array (size=1)
  'x15z' => int 1

我正在尝试查找两个关联数组之间的差异,并且我目前正在尝试使用array_diff_assoc($ array1,$ array2),并且在上述一个实例中一个元素从另一个元素丢失的情况下可以使用,区别是

I am trying to find the difference between the two associative arrays and I am currently trying to use array_diff_assoc($array1, $array2) and this works in the case whereby one element is missing from the other however in the instance described above, the difference is

array (size=2)
  'x15z' => int '12' (length=2)
  'x16z' => int '3' (length=1)

与我正在寻找的是相反的:

as opposed to what I am looking for which is:

array (size=2)
  'x15z' => int '11' (length=2)
  'x16z' => int '3' (length=1)

据此还计算了值差.

是否有任何逻辑方法可以根据两个关联数组的键和值来计算它们的差?谢谢!

Is there any logical way to calculate the difference of two associative arrays based upon their keys and values? Thanks!

推荐答案

function calculateDifference($array1, $array2){
  $difference = array();
  foreach($array1 as $key => $value){
    if(isset($array2[$key])){
      $difference[$key] = abs($array1[$key] - $array2[$key]);
    }else{
      $difference[$key] = $value;
    }
  }
  foreach($array2 as $key => $value){
    if(isset($array1[$key])){
      $difference[$key] = abs($array1[$key] - $array2[$key]);
    }else{
      $difference[$key] = $value;
    }
  }
  return $difference;
}

这篇关于PHP通过键和值比较两个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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