PHP合并多个API接口数据至数组问题求助
合并多个Albion Online API公会成员数据的问题
我想要编写一个小型函数,将多个Albion Online API接口返回的公会成员数据加载并合并到一个数组中以便使用。当前我的代码如下:
$url1 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/uhmotNBAQ6-0vi9PFysRBg/members'; $url2 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/DWkD4B0uSsGQoryrz8Nuwg/members'; $url3 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/wSbCgimqTPy470n-wDQXPQ/members'; $url4 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/nmc0HQW-TZirTlnGzwbF-w/members'; $url5 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/WpV4yaVxSLW8QXH2Be40cA/members'; $api_endpoint1 = json_decode(file_get_contents($url1), true); $api_endpoint2 = json_decode(file_get_contents($url2), true); $api_endpoint3 = json_decode(file_get_contents($url3), true); $api_endpoint4 = json_decode(file_get_contents($url4), true); $api_endpoint5 = json_decode(file_get_contents($url5), true); $merged_data = array(); foreach ($api_endpoint1 as $data) { foreach ($api_endpoint2 as $data2) { $merged_data[] = array_merge($data, $data2[$data['Name']]); } } var_dump($merged_data);
但这段代码无法正常运行,我过去两天尝试了多种方法都没有解决,特此寻求帮助。
问题分析与解决方案
原代码的核心错误
- 逻辑错误:嵌套循环会把第一个公会的每个成员和第二个公会的每个成员强行合并,完全不符合“合并多个公会成员列表”的需求。
- 数据结构误解:每个API返回的是成员对象的数组,不存在
data2[$data['Name']]这种索引结构,直接访问会触发未定义索引错误。 - 冗余重复:逐个定义URL和解析变量,代码冗余且难以维护。
正确实现代码
// 把所有公会API URL存入数组,便于后续维护 $guildUrls = [ 'https://gameinfo.albiononline.com/api/gameinfo/guilds/uhmotNBAQ6-0vi9PFysRBg/members', 'https://gameinfo.albiononline.com/api/gameinfo/guilds/DWkD4B0uSsGQoryrz8Nuwg/members', 'https://gameinfo.albiononline.com/api/gameinfo/guilds/wSbCgimqTPy470n-wDQXPQ/members', 'https://gameinfo.albiononline.com/api/gameinfo/guilds/nmc0HQW-TZirTlnGzwbF-w/members', 'https://gameinfo.albiononline.com/api/gameinfo/guilds/WpV4yaVxSLW8QXH2Be40cA/members' ]; $mergedMembers = []; foreach ($guildUrls as $url) { // 处理API请求,增加错误捕获避免脚本崩溃 $response = file_get_contents($url); if ($response === false) { continue; // 请求失败则跳过当前公会 } $members = json_decode($response, true); // 确保解析结果是有效数组再合并 if (is_array($members)) { $mergedMembers = array_merge($mergedMembers, $members); } } // 可选:根据成员唯一ID去重(避免同一玩家在多个公会的重复数据) $uniqueMembers = []; foreach ($mergedMembers as $member) { if (isset($member['Id'])) { $uniqueMembers[$member['Id']] = $member; } } // 转换回索引数组(如果需要) $uniqueMembers = array_values($uniqueMembers); var_dump($uniqueMembers);
代码说明
- 批量管理URL:用数组存储所有公会API地址,后续新增公会只需在数组中添加,无需重复编写变量和解析代码。
- 错误处理:增加请求和解析的有效性检查,避免单个API失败导致整个脚本终止。
- 灵活合并:默认直接合并所有成员,若需要去重,使用API返回的
Id字段(唯一标识)作为键,比用Name更可靠(避免重名问题)。
内容的提问来源于stack exchange,提问作者Caleb
相关产品推荐
相关产品推荐

