Get added/removed/changes key=>value pairs between two arrays
I have two multidimensional arrays called $old and $new. I want to compare
the two arrays and see what k=>v's were added, removed, or changed between
the two.
These are the arrays:
$old = array(
'ONE' => array('a' => 1, 'b' => 2, 'c' => 3),
'TWO' => array('a' => 4, 'b' => 5, 'c' => 6),
'THREE' => array('a' => 7, 'b' => 8, 'c' => 9)
);
$new = array(
'TWO' => array('a' => 5, 'b' => 5, 'c' => 6),
'THREE' => array('a' => 7, 'b' => 8, 'c' => 9),
'FOUR' => array('a' => 1, 'b' => 2, 'c' => 3)
);
Notice that in the $new array I have removed 'ONE', added 'FOUR', and
changed the value of 'TWO'=>'a' from 4 to 5.
This is my current (working) solution, but I feel that I don't need to
write this much code and I'm unsure if it will be slow on much larger
arrays.
$added = array();
$removed = array();
$changed = array();
foreach ($old as $old_key => $old_value) {
if (!in_array($old_key, array_keys($new))) {
$removed[] = $old_value;
unset($old[$old_key]);
}
}
foreach ($new as $new_key => $new_value) {
if (!in_array($new_key, array_keys($old))) {
$added[] = $new_value;
unset($new[$new_key]);
}
}
$changed = array_udiff($new, $old, create_function(
'$a,$b',
'return strcmp(implode("", $a), implode("", $b));'
));
No comments:
Post a Comment