<?php
/**
* Maps fields of JSON objects to hard-coded limits for testing.
*
* @param array $data An array of JSON objects.
* @param array $limits An associative array defining field limits (field => limit).
* @return array An array of mapped data.
*/
function mapJsonData(array $data, array $limits): array
{
$mappedData = [];
foreach ($data as $item) {
$mappedItem = [];
foreach ($limits as $field => $limit) {
// Check if the field exists in the item, and if it's numeric
if (array_key_exists($field, $item) && is_numeric($item[$field])) {
$mappedItem[$field] = min($item[$field], $limit); // Apply limit
} else {
$mappedItem[$field] = $item[$field]; // Keep original value if not numeric or field doesn't exist
}
}
$mappedData[] = $mappedItem;
}
return $mappedData;
}
// Example usage:
// Define your JSON data (as an array of associative arrays)
$jsonData = [
['id' => 1, 'value' => 150, 'age' => 30],
['id' => 2, 'value' => 200, 'age' => 25],
['id' => 3, 'value' => 100, 'age' => 40],
['id' => 4, 'name' => 'test'] //added test case without 'value' and 'age'
];
// Define your limits
$limits = [
'value' => 180,
'age' => 35,
];
// Map the data
$mappedData = mapJsonData($jsonData, $limits);
// Output the mapped data (for testing)
print_r($mappedData);
?>
Add your comment