我有 2 个关联数组,如下所示。
Array
(
[Turbine] => 0
[Nuts and Bolts] => 6
[Runner Blade] => 5
)
Array
(
[Nuts and Bolts] => 10
[Runner Blade] => 5
[Turbine] => 1
)
我想要做的是比较两个数组并返回具有相同键但不同值的数组。与
array_intersect_assoc
类似,但它返回所有匹配的值,这不是我想要的。使用上面的示例,我想要返回的是两个值之间的差异,例如:
Array
(
[Nuts and Bolts] => 4
[Turbine] => 1
)
类似这样的:
$ar1;
$ar2;
foreach ($ar1 as $k => $v) {
if (intval($ar2[$k]) != intval($v))
$ar1[$k] = abs($v - $ar2[$k]);
else
unset($ar1[$k]); // remove key with equal value
}
试试这个...
$newArr = array();
foreach($arr1 as $k=>$v){
$dif = abs($arr1[$k] - $arr2[$k]);
if($dif) $newArr[$k] = $dif;
}
print '<pre>';
print_r($newArr);
这将实现你想要的:
array_intersect_key($array1, $array2)
$diff = array_diff_assoc($arr1, $arr2);
$result = array();
foreach(array_keys($diff) as $key){
$result[$key] = abs($arr1[$key] - $arr2[$key]);
}
var_dump($result);
试试这个:
function compareArrays($array1, $array2, $path = "") {
$differences = [];
foreach ($array1 as $key => $value1) {
$path1 = $path . "[" . $key . "]";
if (array_key_exists($key, $array2)) {
$value2 = $array2[$key];
if (is_array($value1) && is_array($value2)) {
$subDifferences = compareArrays($value1, $value2, $path1);
$differences = array_merge($differences, $subDifferences);
} else {
if ($value1 !== $value2) {
$differences[$path1] = $value1;
}
}
} else {
$differences[$path1] = $value1;
}
}
return $differences;
}
$array1 = array(
"name" => "John",
"age" => 30,
"address" => array(
"city" => "New York",
"zipcode" => "10001"
)
);
$array2 = array(
"name" => "Alice",
"age" => 25,
"address" => array(
"city" => "Los Angeles",
"zipcode" => "90001"
)
);
$differences = compareArrays($array1, $array2);
foreach ($differences as $key => $value) {
echo "Key: $key, Value: $value\n";
}
此代码的输出将是:
Key: [name], Value: John
Key: [age], Value: 30
Key: [address][city], Value: New York
Key: [address][zipcode], Value: 10001
Key: [name], Value: Alice
Key: [age], Value: 25
Key: [address][city], Value: Los Angeles
Key: [address][zipcode], Value: 90001