1. <?php
  2. /**
  3. * Function to replace values in an API response for data migration.
  4. *
  5. * @param array $response The API response data (as an associative array).
  6. * @param array $replacements An associative array of key => new_value pairs.
  7. * @return array The modified API response.
  8. */
  9. function migrateData(array $response, array $replacements): array
  10. {
  11. // Iterate through the replacements array.
  12. foreach ($replacements as $key => $new_value) {
  13. // Check if the key exists in the response.
  14. if (array_key_exists($key, $response)) {
  15. // Replace the value if it exists.
  16. $response[$key] = $new_value;
  17. }
  18. }
  19. return $response;
  20. }
  21. /**
  22. * Example usage.
  23. */
  24. // Sample API response.
  25. $apiResponse = [
  26. 'id' => 123,
  27. 'name' => 'Old Name',
  28. 'email' => 'old.email@example.com',
  29. 'status' => 'inactive',
  30. 'created_at' => '2023-10-26',
  31. ];
  32. // Define the replacements.
  33. $replacements = [
  34. 'name' => 'New Name',
  35. 'email' => 'new.email@example.com',
  36. 'status' => 'active'
  37. ];
  38. // Migrate the data.
  39. $migratedResponse = migrateData($apiResponse, $replacements);
  40. // Output the migrated response.
  41. print_r($migratedResponse);
  42. ?>

Add your comment