You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用COVID-19 API按输入国家查询数据报错咨询

报错原因
  • 你调用json_decode($data, true)时传入了第二个参数true,该配置会把所有JSON结构解析为PHP关联数组,不支持用->对象属性语法读取,必须通过数组下标[]取值。
  • $corona['Countries']是存储所有国家数据的索引数组,每个下标对应一个国家的单独数据,Country字段归属于每个单独的国家子项,并非Countries节点的直接属性,直接读取必然报错。
正确实现代码

要实现用户输入国家名后匹配对应数据,只需要遍历Countries数组,匹配到和用户输入一致的国家项后输出对应字段即可,参考代码如下:

// 请求接口并解析数据
$data = file_get_contents("https://api.covid19api.com/summary");
$corona = json_decode($data, true);
$countryList = $corona['Countries'];

// 接收用户传入的国家名称,根据你的表单提交方式修改取值逻辑即可
$inputCountry = trim($_REQUEST['country'] ?? '');
$targetCountryData = null;

// 遍历国家列表匹配名称
foreach ($countryList as $countryItem) {
    // 大小写不敏感匹配,避免用户输入大小写和接口返回格式不一致导致匹配失败
    if (strcasecmp($countryItem['Country'], $inputCountry) === 0) {
        $targetCountryData = $countryItem;
        break;
    }
}

// 输出查询结果
if ($targetCountryData) {
    echo "<br>Country : " . $targetCountryData["Country"];
    echo "<br>Total Confirmed : " . $targetCountryData["TotalConfirmed"];
    echo "<br>Total Deaths : " . $targetCountryData["TotalDeaths"];
    echo "<br>Total Recovered : " . $targetCountryData["TotalRecovered"];
} else {
    echo "<br>未查询到对应国家数据,请检查输入的国家名称是否正确";
}

小提示:如果偏好对象操作语法,可以把json_decode的第二个参数设为false(或直接不传),此时返回结果为PHP对象,用->语法取值即可,遍历匹配的逻辑和上面完全一致。

内容的提问来源于stack exchange,提问作者Spooky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.06 16:15:42