I have two arrays I want to compare:
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"
}
Here is my code:
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');
My result is:
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
But what I would need is this:
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
That means, at first I want to display that there is an error for a specific animal with a specific name. After this, I want to display the differences. that means always the value of animal1
and after that the value of animal2
.
I do not know how to change my code the best way to achieve the result I wish.
This is the output of 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