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