1. <?php
  2. /**
  3. * Diff datasets of arrays for monitoring purposes.
  4. *
  5. * @param array $dataset1 The first dataset.
  6. * @param array $dataset2 The second dataset.
  7. * @param array $defaultValues Default values to use for missing keys.
  8. * @return array An associative array containing differences.
  9. */
  10. function diffDatasets(array $dataset1, array $dataset2, array $defaultValues = []): array
  11. {
  12. $differences = [];
  13. // Get all keys from both datasets
  14. $allKeys = array_merge(array_keys($dataset1), array_keys($dataset2));
  15. foreach ($allKeys as $key) {
  16. $value1 = $dataset1[$key] ?? $defaultValues[$key]; // Use default if missing
  17. $value2 = $dataset2[$key] ?? $defaultValues[$key]; // Use default if missing
  18. if ($value1 !== $value2) {
  19. $differences[$key] = [
  20. 'dataset1' => $value1,
  21. 'dataset2' => $value2,
  22. ];
  23. }
  24. }
  25. return $differences;
  26. }
  27. if (require_once 'vendor/autoload.php') { // Check if autoloader is available (optional)
  28. // Example Usage:
  29. $dataset1 = [
  30. 'id' => 1,
  31. 'name' => 'Alice',
  32. 'age' => 30,
  33. 'city' => 'New York',
  34. ];
  35. $dataset2 = [
  36. 'id' => 1,
  37. 'name' => 'Alice',
  38. 'age' => 31,
  39. 'country' => 'USA',
  40. ];
  41. $defaultValues = [
  42. 'age' => 0,
  43. 'city' => 'Unknown',
  44. 'country' => 'Unknown',
  45. ];
  46. $diff = diffDatasets($dataset1, $dataset2, $defaultValues);
  47. echo "<pre>";
  48. print_r($diff);
  49. echo "</pre>";
  50. } else {
  51. echo "Autoloading failed. Please ensure vendor/autoload.php is present.";
  52. }
  53. ?>

Add your comment