Last active
April 11, 2019 20:46
-
-
Save iprodev/2e93bed7ab858a94fcf40fb92341ccc7 to your computer and use it in GitHub Desktop.
PHP : Computes the difference between multidimensional arrays
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
<?php | |
/** | |
* Computes the difference between two arrays | |
* | |
* @param array $array1 | |
* @param array $array2 | |
* @return array | |
*/ | |
function array_diff_two( $array1, $array2 ) { | |
$diff = array(); | |
// Check the similarities | |
foreach( $array1 as $k1 => $v1 ) { | |
if ( isset( $array2[$k1] ) ) { | |
$v2 = $array2[$k1]; | |
if ( is_array( $v1 ) && is_array( $v2 ) ){ | |
// 2 arrays: just go further... | |
// .. and explain it's an update! | |
$changes = array_diff_two( $v1, $v2 ); | |
if ( count( $changes ) > 0 ){ | |
// If we have no change, simply ignore | |
$diff[$k1] = $changes; | |
} | |
unset( $array2[$k1] ); // don't forget | |
} | |
else if ( $v2 === $v1 ){ | |
// unset the value on the second array | |
// for the "surplus" | |
unset( $array2[$k1] ); | |
} | |
else { | |
// Don't mind if arrays or not. | |
$diff[$k1] = $v2; | |
unset( $array2[$k1] ); | |
} | |
} | |
else { | |
// remove information | |
$diff[$k1] = $v1; | |
} | |
} | |
reset( $array2 ); | |
foreach ( $array2 as $key => $value ){ | |
$diff[$key] = $value; | |
} | |
return $diff; | |
} | |
/** | |
* Computes the difference of arrays | |
* | |
* @param array $array1 | |
* @param array $array2 | |
* @param array $... | |
* @return array | |
*/ | |
function array_difference() { | |
$arguments = func_get_args(); | |
$diff = array(); | |
foreach ( $arguments as $key => $array ) { | |
$diff = array_diff_two( $diff, $array ); | |
} | |
return $diff; | |
} | |
$array1 = array( | |
"a" => "green", | |
"b" => array( | |
"id" => 1, | |
"ids" => 1 | |
), | |
"red" | |
); | |
$array2 = array( | |
"a" => "green", | |
"b" => array( | |
"id" => 2 | |
), | |
"yellow", | |
"red" | |
); | |
$array3 = array( | |
"a" => "blue", | |
"b" => array(), | |
"navy", | |
"red" | |
); | |
$result = array_difference( $array1, $array2, $array3 ); | |
print_r($result); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment