<?php
/**
* Matches user records against patterns defined in a configuration file.
*
* @param string $config_file Path to the configuration file.
* @param array $user_records Array of user records (e.g., associative arrays).
* @return array Associative array of matched user records, keyed by pattern name.
*/
function matchUserRecords(string $config_file, array $user_records): array
{
// Load the configuration file.
$config = loadConfig($config_file);
if (!$config) {
return []; // Return empty array if config loading fails.
}
$matched_users = [];
// Iterate through the user records.
foreach ($user_records as $user_id => $user) {
// Iterate through the patterns in the configuration.
foreach ($config['patterns'] as $pattern_name => $pattern) {
if (matchesPattern($user, $pattern)) {
// Add the user to the matched users array.
if (!isset($matched_users[$pattern_name])) {
$matched_users[$pattern_name] = [];
}
$matched_users[$pattern_name][] = $user;
}
}
}
return $matched_users;
}
/**
* Loads the configuration file.
*
* @param string $config_file Path to the configuration file.
* @return array|null Config array, or null on failure.
*/
function loadConfig(string $config_file): ?array
{
// Check if the file exists.
if (!file_exists($config_file)) {
return null;
}
// Read the configuration file.
$config = file_get_contents($config_file);
if ($config === false) {
return null;
}
// Decode the configuration file as an array.
$config = json_decode($config, true);
if ($config === null) {
return null;
}
return $config;
}
/**
* Checks if a user record matches a pattern.
*
* @param array $user User record.
* @param array $pattern Pattern definition.
* @return bool True if the user matches the pattern, false otherwise.
*/
function matchesPattern(array $user, array $pattern): bool
{
// Check if the pattern is an array.
if (!is_array($pattern)) {
return false; // Invalid pattern format.
}
// Check if the user data matches the pattern criteria.
foreach ($pattern['conditions'] as $field => $value) {
// Check if the field exists in the user data.
if (!isset($user[$field])) {
return false; // Field not found in user data.
}
// Compare the field value with the pattern value.
if ($user[$field] !== $value) {
return false; // Field value does not match.
}
}
return true; // User matches the pattern.
}
// Example usage (for testing):
/*
$user_records = [
1 => ['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
2 => ['name' => 'Bob', 'age' => 25, 'city' => 'Los Angeles'],
3 => ['name' => 'Charlie', 'age' => 30, 'city' => 'Chicago'],
];
$config_file = 'config.json'; // Create a config.json file with your patterns
$matched_users = matchUserRecords($config_file, $user_records);
print_r($matched_users);
*/
?>
Add your comment