<?php
/**
* Matches patterns against datasets with defensive checks.
*
* @param array $dataset The dataset to search within.
* @param array $patterns An array of patterns to match. Each pattern should be an array of conditions.
* @return array An array of matching data points.
*/
function matchPatterns(array $dataset, array $patterns): array
{
$matches = [];
// Defensive check: Ensure dataset is an array
if (!is_array($dataset)) {
error_log("Error: Dataset must be an array.");
return [];
}
// Defensive check: Ensure patterns is an array
if (!is_array($patterns)) {
error_log("Error: Patterns must be an array.");
return [];
}
foreach ($dataset as $dataPoint) {
$isMatch = true;
foreach ($patterns as $pattern) {
// Defensive check: Ensure pattern is an array
if (!is_array($pattern)) {
error_log("Error: Each pattern must be an array.");
$isMatch = false; // Skip this pattern if it's invalid.
continue;
}
$match = true;
foreach ($pattern as $condition) {
// Defensive check: Ensure condition is an array or scalar
if (!is_array($condition) && !is_scalar($condition)) {
error_log("Error: Each condition must be an array or scalar.");
$match = false;
break; // Stop checking this pattern if a condition is invalid.
}
// Apply condition. Handle different condition types.
if (is_array($condition)) {
//Example using array_intersect
if (!array_intersect($dataPoint, $condition)) {
$match = false;
break;
}
} else {
//Simple scalar comparison
if ($condition !== $dataPoint) {
$match = false;
break;
}
}
}
if (!$match) {
$isMatch = false;
break; // Stop checking patterns if one fails.
}
}
if ($isMatch) {
$matches[] = $dataPoint;
}
}
return $matches;
}
//Example Usage:
/*
$data = [
['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
['name' => 'Bob', 'age' => 25, 'city' => 'London'],
['name' => 'Charlie', 'age' => 30, 'city' => 'Paris']
];
$patterns = [
['age' => 30], //Match people with age 30
['city' => 'London'], //Match people from London
['age' => 25, 'city' => 'London'] //Match people with age 25 from London
];
$matchingData = matchPatterns($data, $patterns);
print_r($matchingData);
*/
?>
Add your comment