<?php
function getArrayDiff($a1, $a2) {
$result = array();
print_r($a1);
print_r($a2);
// If First Array is Bigger than Second
if(count($a1) > count($a2)) {
$result=array_diff($a1,$a2);
}
// If Second Array is Bigger than First
if(count($a1) < count($a2)) {
$result=array_diff($a2,$a1);
}
// If Both array are same but, data values are different.
else
{
$result = array_merge (array_diff($a2,$a1), array_diff($a1,$a2));
}
return $result;
}
print "<pre>";
// First Array is Big
echo "First Array is Big <br/>";
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
print_r(getArrayDiff($a1, $a2));
// Second Array is Big
echo "Second Array is Big <br/>";
$a1=array("e"=>"red","f"=>"green","g"=>"blue");
$a2=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(getArrayDiff($a1, $a2));
// Both Array are same
echo "Both Array are same <br/>";
$a1=array("a"=>"red","b"=>"green","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
print_r(getArrayDiff($a1, $a2));
?>
輸出:
First Array is Big
Array
(
[a] => red
[b] => green
[c] => blue
[d] => yellow
)
Array
(
[e] => red
[f] => green
[g] => blue
)
Array
(
[d] => yellow
)
Second Array is Big
Array
(
[e] => red
[f] => green
[g] => blue
)
Array
(
[a] => red
[b] => green
[c] => blue
[d] => yellow
)
Array
(
[d] => yellow
)
Both Array are same
Array
(
[a] => red
[b] => green
[d] => yellow
)
Array
(
[e] => red
[f] => green
[g] => blue
)
Array
(
[g] => blue
[d] => yellow
)
這似乎是不正確的 - 它不會從'$ array1'中不存在的'$ array2'返回值。 [Crasherspeeder](http://stackoverflow.com/questions/10077840/difference-between-two-arrays/10077920#10077920)似乎是正確的。 – Shog9 2012-10-15 16:12:31
@Crasherspeeder是正確的,這是一個單向檢查 - 提問者既要。 – 2013-11-07 03:35:42