1. <?php
  2. /**
  3. * Converts array formats for hypothesis validation with retry logic.
  4. *
  5. * @param array $array The input array.
  6. * @param string $targetFormat The desired format (e.g., 'key => value', 'array', 'flat').
  7. * @param int $maxRetries Maximum number of retries.
  8. * @return array|null The converted array, or null on failure after max retries.
  9. */
  10. function convertArrayFormat(array $array, string $targetFormat, int $maxRetries = 3): ?array
  11. {
  12. $retries = 0;
  13. while ($retries < $maxRetries) {
  14. $convertedArray = null;
  15. switch ($targetFormat) {
  16. case 'key => value':
  17. $convertedArray = [];
  18. foreach ($array as $key => $value) {
  19. $convertedArray[$key] = $value;
  20. }
  21. break;
  22. case 'array':
  23. $convertedArray = $array; // No conversion needed
  24. break;
  25. case 'flat':
  26. $convertedArray = [];
  27. foreach ($array as $key => $value) {
  28. $convertedArray[$key] = $value;
  29. }
  30. break;
  31. default:
  32. error_log("Unsupported target format: " . $targetFormat);
  33. return null;
  34. }
  35. if ($convertedArray !== null) {
  36. return $convertedArray; // Conversion successful
  37. } else {
  38. $retries++;
  39. // Optionally add a delay between retries
  40. sleep(0.5);
  41. }
  42. }
  43. error_log("Array format conversion failed after " . $maxRetries . " retries.");
  44. return null; // Conversion failed after all retries
  45. }
  46. ?>

Add your comment