我有兩個數組我想比較:如何比較兩個數組並顯示每個鍵(多維數組)的差異?
animals1:
array(4) {
["1234"]=>
array(5) {
["animal"]=>
string(19) "cat"
["name"]=>
string(12) "fred"
["food"]=>
string(32) "milk"
}
["5678"]=>
array(5) {
["animal"]=>
string(19) "dog"
["name"]=>
string(12) "sam"
["food"]=>
string(32) "chicken"
}
["shop"]=>
string(12) "petcenter"
}
animals2:
array(4) {
["1234"]=>
array(5) {
["animal"]=>
string(19) "cat"
["name"]=>
string(12) "tom"
["food"]=>
string(32) "juice"
}
["5678"]=>
array(5) {
["animal"]=>
string(19) "dog"
["name"]=>
string(12) "sam"
["food"]=>
string(32) "fish"
}
["shop"]=>
string(12) "petcenter"
}
這裏是我的代碼:
foreach ($animals1 as $k1 => $v1) {
if (array_diff($animals2[$k1], $animals1[$k1])){
$diff[$k1] = array_diff($animals2[$k1], $animals1[$k1]);
}
}
foreach ($animals2 as $k1 => $v1) {
if (array_diff($animals1[$k1], $animals2[$k1])){
$diff2[$k1] = array_diff($animals1[$k1], $animals2[$k1]);
}
}
function result1($item, $key){
echo $key."1 = ".$item;
echo "<br>";
}
function result2($item, $key){
echo $key."2 = ".$item;
echo "<br>";
}
foreach ($diff as $d => $key){
foreach ($animals1 as $p => $row) {
if ($p == $d){
echo "Error for animal".$row["animal"];
echo "with the name:".$row["name"].".";
}
}
}
array_walk_recursive($diff, 'result1');
array_walk_recursive($diff2, 'result2');
我的結果是:
Error for animal cat with name fred.
Error for animal dog with name sam.
name1 = fred
food1 = milk
food1 = chicken
name2 = tom
food2 = juice
food2 = fish
但我需要的是:
Error for animal cat with name fred.
name1 = fred
name2 = tom
food1 = milk
food2 = juice
Error for animal dog with name sam.
food1 = chicken
food2 = fish
這意味着,首先我要顯示存在具有特定名稱的特定動物的錯誤。在此之後,我想顯示差異。那意味着始終爲animal1
的值,之後的值爲animal2
。 我不知道如何改變我的代碼,以達到我想要的效果。
這是Standej的輸出:
Error for animal cat with name fred.
name1 = fred
food1 = milk
food1 = chicken
name2 = tom
food2 = juice
food2 = fish
Error for animal dog with name sam.
name1 = fred
food1 = milk
food1 = chicken
name2 = tom
food2 = juice
food2 = fish
[PHP 2點多維數組差(的可能的複製http://stackoverflow.com/questions/27856743/ php-two-multidimensional-array-difference) –
@Elias Nicolas我需要以不同的方式比較不同的密鑰 – Jarla
如果使用'array_diff'則會導致奇怪的結果,如果一個cat的'name'值等於其他貓,反之亦然。 – trincot