<?php
/**
* Flags anomalies in collections for routine automation with fallback logic.
*
* @param array $collection The collection to analyze.
* @param array $thresholds An array of thresholds for anomaly detection. Key is the metric name, value is the threshold.
* @param string $anomaly_level The level of anomaly to flag ('high', 'medium', 'low').
* @return array An array of flagged anomalies with details.
*/
function flagCollectionAnomalies(array $collection, array $thresholds, string $anomaly_level = 'medium'): array
{
$anomalies = [];
foreach ($collection as $item) {
foreach ($thresholds as $metric => $threshold) {
// Check if the metric exists in the item
if (isset($item[$metric])) {
$value = $item[$metric];
// Anomaly detection logic (example: comparing to threshold)
if ($value > $threshold) {
$anomaly_details = [
'item' => $item,
'metric' => $metric,
'value' => $value,
'threshold' => $threshold,
'level' => $anomaly_level,
'reason' => "Value exceeds threshold",
];
$anomalies[] = $anomaly_details;
} elseif ($value < $threshold) {
$anomaly_details = [
'item' => $item,
'metric' => $metric,
'value' => $value,
'threshold' => $threshold,
'level' => $anomaly_level,
'reason' => "Value falls below threshold",
];
$anomalies[] = $anomaly_details;
}
}
}
}
// Fallback logic: If no anomalies are found, return a message.
if (empty($anomalies)) {
$anomalies[] = [
'message' => 'No anomalies detected.',
'level' => 'low',
];
}
return $anomalies;
}
//Example Usage (Can be removed for standalone code)
/*
$data = [
['temperature' => 28, 'humidity' => 60],
['temperature' => 30, 'humidity' => 65],
['temperature' => 25, 'humidity' => 55],
];
$thresholds = ['temperature' => 27, 'humidity' => 62];
$anomalies = flagCollectionAnomalies($data, $thresholds, 'high');
print_r($anomalies);
*/
?>
Add your comment