您可以编写一个函数来提取这两个响应。然后根据成功的结果合并结果。
这假设两个调用的结果都是json数据,应该转换为数组。我还使用了与您提供的相同的函数调用,因此在需要时调整第二个函数。
function get_json_data_from_2apis($api1_data = array(), $api2_data = array())
{
// prepare request data
$api1_json = json_encode($api1_data);
$api2_json = json_encode($api2_data);
// prep the results
$result = array();
// FIRST CALL
$response = wp_remote_get(\'https://api1.endpoint.com\', array(
\'headers\' => array(
\'Content-Type\' => \'application/json\',
\'X-Api-Token\' => \'tokenid\',
\'X-Api-Email\' => \'tokenemail\',
),
\'body\' => $api1_json,
));
if( ! is_wp_error($response)) {
if(200 == wp_remote_retrieve_response_code($response)) {
$body = wp_remote_retrieve_body($response);
// store the first answer --- convert body to array
$result [ \'api1\' ] = array(\'success\' => true, \'data\' => json_decode($body, true));
}
else {
$result [ \'api1\' ] = array(\'success\' => false);
}
}
else {
$error_message = $response->get_error_message();
$result [ \'api1\' ] = array(\'success\' => false, \'data\' => $error_message);
}
// SECOND CALL
$response = wp_remote_get(\'https://api2.endpoint.com\', array(
\'headers\' => array(
\'Content-Type\' => \'application/json\',
\'X-Api-Token\' => \'tokenid\',
\'X-Api-Email\' => \'tokenemail\',
),
\'body\' => $api2_json,
));
if( ! is_wp_error($response)) {
if(200 == wp_remote_retrieve_response_code($response)) {
$body = wp_remote_retrieve_body($response);
// store the second answer --- convert body to array
$result [ \'api2\' ] = array(\'success\' => true, \'data\' => json_decode($body, true));
}
else {
$result [ \'api2\' ] = array(\'success\' => false);
}
}
else {
$error_message = $response->get_error_message();
$result [ \'api2\' ] = array(\'success\' => false, \'data\' => $error_message);
}
return $result;
}
调用函数以返回两个结果:
$results = get_json_data_from_2apis(array(), NULL);
如果两者都成功,请合并响应。
if($results[ \'api1\' ][ \'success\' ] === true && $results[ \'api2\' ][ \'success\' ] === true) {
// merge the results
$final = array_merge($results[ \'api1\' ][ \'data\' ], $results[ \'api1\' ][ \'data\' ]);
// print them out
print_r($final);
}