1. <?php
  2. /**
  3. * Aggregates values from multiple HTTP responses.
  4. *
  5. * @param array $responses An array of HTTP response objects. Each object should have a 'body' property.
  6. * @return array An associative array where keys are unique identifiers and values are aggregated values.
  7. */
  8. function aggregateResponses(array $responses): array
  9. {
  10. $aggregatedData = [];
  11. foreach ($responses as $response) {
  12. // Assuming each response has a 'body' property containing the data.
  13. $body = $response['body'];
  14. // Check if body exists and is an array. Important for resilience.
  15. if (is_array($body)) {
  16. foreach ($body as $item) {
  17. // Check if the item has a unique identifier (e.g., 'id').
  18. if (isset($item['id'])) {
  19. $id = $item['id'];
  20. // Initialize the aggregated value if it doesn't exist.
  21. if (!isset($aggregatedData[$id])) {
  22. $aggregatedData[$id] = [];
  23. }
  24. // Add the item's value to the corresponding array.
  25. $aggregatedData[$id][] = $item['value']; //assuming each item has a 'value' property
  26. }
  27. }
  28. } else {
  29. //Handle the case where the body is not an array. Log, warn, or skip.
  30. error_log("Warning: Response body is not an array. Skipping.");
  31. }
  32. }
  33. return $aggregatedData;
  34. }
  35. // Example usage (assuming you have some HTTP response objects)
  36. /*
  37. $response1 = ['body' => [
  38. ['id' => 1, 'value' => 10],
  39. ['id' => 2, 'value' => 20],
  40. ]];
  41. $response2 = ['body' => [
  42. ['id' => 1, 'value' => 15],
  43. ['id' => 3, 'value' => 30],
  44. ]];
  45. $responses = [$response1, $response2];
  46. $aggregatedResult = aggregateResponses($responses);
  47. print_r($aggregatedResult);
  48. */
  49. ?>

Add your comment