1. <?php
  2. /**
  3. * Flags anomalies in collections for routine automation with fallback logic.
  4. *
  5. * @param array $collection The collection to analyze.
  6. * @param array $thresholds An array of thresholds for anomaly detection. Key is the metric name, value is the threshold.
  7. * @param string $anomaly_level The level of anomaly to flag ('high', 'medium', 'low').
  8. * @return array An array of flagged anomalies with details.
  9. */
  10. function flagCollectionAnomalies(array $collection, array $thresholds, string $anomaly_level = 'medium'): array
  11. {
  12. $anomalies = [];
  13. foreach ($collection as $item) {
  14. foreach ($thresholds as $metric => $threshold) {
  15. // Check if the metric exists in the item
  16. if (isset($item[$metric])) {
  17. $value = $item[$metric];
  18. // Anomaly detection logic (example: comparing to threshold)
  19. if ($value > $threshold) {
  20. $anomaly_details = [
  21. 'item' => $item,
  22. 'metric' => $metric,
  23. 'value' => $value,
  24. 'threshold' => $threshold,
  25. 'level' => $anomaly_level,
  26. 'reason' => "Value exceeds threshold",
  27. ];
  28. $anomalies[] = $anomaly_details;
  29. } elseif ($value < $threshold) {
  30. $anomaly_details = [
  31. 'item' => $item,
  32. 'metric' => $metric,
  33. 'value' => $value,
  34. 'threshold' => $threshold,
  35. 'level' => $anomaly_level,
  36. 'reason' => "Value falls below threshold",
  37. ];
  38. $anomalies[] = $anomaly_details;
  39. }
  40. }
  41. }
  42. }
  43. // Fallback logic: If no anomalies are found, return a message.
  44. if (empty($anomalies)) {
  45. $anomalies[] = [
  46. 'message' => 'No anomalies detected.',
  47. 'level' => 'low',
  48. ];
  49. }
  50. return $anomalies;
  51. }
  52. //Example Usage (Can be removed for standalone code)
  53. /*
  54. $data = [
  55. ['temperature' => 28, 'humidity' => 60],
  56. ['temperature' => 30, 'humidity' => 65],
  57. ['temperature' => 25, 'humidity' => 55],
  58. ];
  59. $thresholds = ['temperature' => 27, 'humidity' => 62];
  60. $anomalies = flagCollectionAnomalies($data, $thresholds, 'high');
  61. print_r($anomalies);
  62. */
  63. ?>

Add your comment