1. <?php
  2. /**
  3. * Maps fields of JSON objects to hard-coded limits for testing.
  4. *
  5. * @param array $data An array of JSON objects.
  6. * @param array $limits An associative array defining field limits (field => limit).
  7. * @return array An array of mapped data.
  8. */
  9. function mapJsonData(array $data, array $limits): array
  10. {
  11. $mappedData = [];
  12. foreach ($data as $item) {
  13. $mappedItem = [];
  14. foreach ($limits as $field => $limit) {
  15. // Check if the field exists in the item, and if it's numeric
  16. if (array_key_exists($field, $item) && is_numeric($item[$field])) {
  17. $mappedItem[$field] = min($item[$field], $limit); // Apply limit
  18. } else {
  19. $mappedItem[$field] = $item[$field]; // Keep original value if not numeric or field doesn't exist
  20. }
  21. }
  22. $mappedData[] = $mappedItem;
  23. }
  24. return $mappedData;
  25. }
  26. // Example usage:
  27. // Define your JSON data (as an array of associative arrays)
  28. $jsonData = [
  29. ['id' => 1, 'value' => 150, 'age' => 30],
  30. ['id' => 2, 'value' => 200, 'age' => 25],
  31. ['id' => 3, 'value' => 100, 'age' => 40],
  32. ['id' => 4, 'name' => 'test'] //added test case without 'value' and 'age'
  33. ];
  34. // Define your limits
  35. $limits = [
  36. 'value' => 180,
  37. 'age' => 35,
  38. ];
  39. // Map the data
  40. $mappedData = mapJsonData($jsonData, $limits);
  41. // Output the mapped data (for testing)
  42. print_r($mappedData);
  43. ?>

Add your comment