DiffArray.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Provides helpers to perform diffs on multi dimensional arrays.
  5. *
  6. * @ingroup utility
  7. */
  8. class DiffArray {
  9. /**
  10. * Recursively computes the difference of arrays with additional index check.
  11. *
  12. * This is a version of array_diff_assoc() that supports multidimensional
  13. * arrays.
  14. *
  15. * @param array $array1
  16. * The array to compare from.
  17. * @param array $array2
  18. * The array to compare to.
  19. *
  20. * @return array
  21. * Returns an array containing all the values from array1 that are not present
  22. * in array2.
  23. */
  24. public static function diffAssocRecursive(array $array1, array $array2) {
  25. $difference = [];
  26. foreach ($array1 as $key => $value) {
  27. if (is_array($value)) {
  28. if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
  29. $difference[$key] = $value;
  30. }
  31. else {
  32. $new_diff = static::diffAssocRecursive($value, $array2[$key]);
  33. if (!empty($new_diff)) {
  34. $difference[$key] = $new_diff;
  35. }
  36. }
  37. }
  38. elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
  39. $difference[$key] = $value;
  40. }
  41. }
  42. return $difference;
  43. }
  44. }