<?php
/**
* Aggregates values from multiple HTTP responses.
*
* @param array $responses An array of HTTP response objects. Each object should have a 'body' property.
* @return array An associative array where keys are unique identifiers and values are aggregated values.
*/
function aggregateResponses(array $responses): array
{
$aggregatedData = [];
foreach ($responses as $response) {
// Assuming each response has a 'body' property containing the data.
$body = $response['body'];
// Check if body exists and is an array. Important for resilience.
if (is_array($body)) {
foreach ($body as $item) {
// Check if the item has a unique identifier (e.g., 'id').
if (isset($item['id'])) {
$id = $item['id'];
// Initialize the aggregated value if it doesn't exist.
if (!isset($aggregatedData[$id])) {
$aggregatedData[$id] = [];
}
// Add the item's value to the corresponding array.
$aggregatedData[$id][] = $item['value']; //assuming each item has a 'value' property
}
}
} else {
//Handle the case where the body is not an array. Log, warn, or skip.
error_log("Warning: Response body is not an array. Skipping.");
}
}
return $aggregatedData;
}
// Example usage (assuming you have some HTTP response objects)
/*
$response1 = ['body' => [
['id' => 1, 'value' => 10],
['id' => 2, 'value' => 20],
]];
$response2 = ['body' => [
['id' => 1, 'value' => 15],
['id' => 3, 'value' => 30],
]];
$responses = [$response1, $response2];
$aggregatedResult = aggregateResponses($responses);
print_r($aggregatedResult);
*/
?>
Add your comment