-
-
Save jqlblue/dd913448bd85eeda9706379404c8057c to your computer and use it in GitHub Desktop.
php array diff recursive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function diffRecursive($from, $to, $deleteFlag = false) | |
{ | |
$diffs = []; | |
foreach ($from as $key => $value) { | |
if (array_key_exists($key, $to)) { | |
if (is_array($value)) { | |
$recursiveDiff = diffRecursive($value, $to[$key], $deleteFlag); | |
if (! empty($recursiveDiff)) { | |
$diffs[$key] = $recursiveDiff; | |
} | |
} else { | |
if ($value != $to[$key] && ! $deleteFlag) { | |
$diffs[$key] = 'modify'; | |
} | |
} | |
} else { | |
if ($deleteFlag) { | |
$diffs[$key] = 'delete'; | |
} else { | |
$diffs[$key] = 'add'; | |
} | |
} | |
} | |
return $diffs; | |
} | |
$a = [ | |
'a' => [ | |
'key1' => 1, | |
'key2' => 2, | |
], | |
'b'=> [ | |
'bkey1' => [ | |
'bbkey1' => 'bb1', | |
'bbkey2' => 'bb2', | |
] | |
] | |
]; | |
$b = [ | |
'a' => [ | |
'key1' => 2, | |
'key3' => 2, | |
], | |
'b'=> [ | |
'bkey1' => [ | |
'bbkey1' => 'bb1', | |
'bbkey2' => 'bb2', | |
] | |
] | |
]; | |
$s1 = diffRecursive($a, $b); | |
var_dump($s1); | |
$s2 = diffRecursive($b, $a, true); | |
var_dump($s2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment