fork(8) download
  1. <?php
  2. class Tools{
  3. /**
  4.   * Recursive version of array_diff_assoc
  5.   * Returns everything from $a that is not in $b or the other arguments
  6.   *
  7.   * @param $a The array to compare from
  8.   * @param $b An array to compare against
  9.   * @param ... More arrays to compare against
  10.   *
  11.   * @return An array with everything from $a that not in $b or the others
  12.   */
  13. public static function array_diff_assoc_recursive($a, $b){
  14. // Get all of the "compare against" arrays
  15. // Initial return value
  16. $ret = array();
  17.  
  18. // Loop over the "to" array and compare with the others
  19. foreach($a as $key=>$val){
  20. // We should compare type first
  21. $aType = gettype($val);
  22. // If it's an array, we recurse, otherwise we just compare with "==="
  23. $args = $aType === 'array' ? array($val) : true;
  24.  
  25. // Let's see what we have to compare to
  26. foreach($b as $x){
  27. // If the key doesn't exist or the type is different,
  28. // then it's different, and our work here is done
  29. if(!array_key_exists($key, $x) || $aType !== gettype($x[$key])){
  30. $ret[$key] = $val;
  31. continue 2;
  32. }
  33.  
  34. // If we are working with arrays, then we recurse
  35. if($aType === 'array'){
  36. $args[] = $x[$key];
  37. }
  38. // Otherwise we just compare
  39. else{
  40. $args = $args && $val === $x[$key];
  41. }
  42. }
  43.  
  44. // This is where we call ourselves with all of the arrays we got passed
  45. if($aType === 'array'){
  46. $comp = call_user_func_array(array(get_called_class(), 'array_diff_assoc_recursive'), $args);
  47. // An empty array means we are equal :-)
  48. if(count($comp) > 0){
  49. $ret[$key] = $comp;
  50. }
  51. }
  52. // If the values don't match, then we found a difference
  53. elseif(!$args){
  54. $ret[$key] = $val;
  55. }
  56. }
  57. return $ret;
  58. }
  59. }
  60.  
  61. $a = array(
  62. array(1,2,3),
  63. 4,
  64. array(5,6)
  65. );
  66. $b = array(
  67. array(1,2,3),
  68. 4,
  69. array(5,6)
  70. );
  71. $c = array(
  72. array(1,2),
  73. 4,
  74. array(5,6)
  75. );
  76.  
  77. var_dump(Tools::array_diff_assoc_recursive($a,$b,$c));
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
array(1) {
  [0]=>
  array(1) {
    [2]=>
    int(3)
  }
}