1. <?php
  2. /**
  3. * Diffs two datasets of lists and performs basic sanity checks.
  4. *
  5. * @param array $dataset1 The first dataset (array of lists).
  6. * @param array $dataset2 The second dataset (array of lists).
  7. * @return array An array containing the diff results, including:
  8. * - 'added': Lists present in $dataset2 but not in $dataset1.
  9. * - 'removed': Lists present in $dataset1 but not in $dataset2.
  10. * - 'modified': Lists present in both datasets but with differences.
  11. * - 'errors': Any errors encountered during the comparison.
  12. */
  13. function diffDatasets(array $dataset1, array $dataset2): array
  14. {
  15. $added = [];
  16. $removed = [];
  17. $modified = [];
  18. $errors = [];
  19. // Helper function to compare two lists
  20. function compareLists(array $list1, array $list2): array
  21. {
  22. $diff = [];
  23. $len1 = count($list1);
  24. $len2 = count($list2);
  25. $minLen = min($len1, $len2);
  26. for ($i = 0; $i < $minLen; $i++) {
  27. if ($list1[$i] !== $list2[$i]) {
  28. $diff[] = ['index' => $i, 'value1' => $list1[$i], 'value2' => $list2[$i]];
  29. }
  30. }
  31. if ($len1 > $len2) {
  32. for ($i = $minLen; $i < $len1; $i++) {
  33. $diff[] = ['index' => $i, 'value1' => $list1[$i], 'value2' => null];
  34. }
  35. } elseif ($len2 > $len1) {
  36. for ($i = $minLen; $i < $len2; $i++) {
  37. $diff[] = ['index' => $i, 'value1' => null, 'value2' => $list2[$i]];
  38. }
  39. }
  40. return $diff;
  41. }
  42. // Check if datasets are arrays
  43. if (!is_array($dataset1) || !is_array($dataset2)) {
  44. $errors[] = ['type' => 'invalid_input', 'message' => 'Datasets must be arrays.'];
  45. return ['added' => [], 'removed' => [], 'modified' => [], 'errors' => $errors];
  46. }
  47. // Iterate through the first dataset
  48. foreach ($dataset1 as $list1) {
  49. $found = false;
  50. foreach ($dataset2 as $list2) {
  51. if ($list1 === $list2) {
  52. $found = true;
  53. break;
  54. }
  55. }
  56. if (!$found) {
  57. $removed[] = $list1;
  58. }
  59. }
  60. // Iterate through the second dataset
  61. foreach ($dataset2 as $list2) {
  62. $found = false;
  63. foreach ($dataset1 as $list1) {
  64. if ($list1 === $list2) {
  65. $found = true;
  66. break;
  67. }
  68. }
  69. if (!$found) {
  70. $added[] = $list2;
  71. }
  72. }
  73. // Find modified lists
  74. foreach ($dataset1 as $list1) {
  75. foreach ($dataset2 as $list2) {
  76. if ($list1 === $list2) {
  77. $modified[] = compareLists($list1, $list2);
  78. break;
  79. }
  80. }
  81. }
  82. return [
  83. 'added' => $added,
  84. 'removed' => $removed,
  85. 'modified' => $modified,
  86. 'errors' => $errors,
  87. ];
  88. }
  89. /**
  90. * Example Usage
  91. */
  92. /*
  93. $dataset1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  94. $dataset2 = [[1, 2, 3], [4, 5, 7], [10, 11, 12]];
  95. $diff = diffDatasets($dataset1, $dataset2);
  96. print_r($diff);
  97. */
  98. ?>

Add your comment