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

如何用PHP遍历JSON文件并提取所有记录的City等指定字段

实现代码

你现在只取到第一条是因为用了索引[0]固定取数组第一个元素,直接遍历ResponseLocation数组即可获取所有记录的对应字段。

直接遍历输出所有城市

$response = curl_exec($ch);
$result = json_decode($response, true);

foreach ($result['GetLocationsResult']['ResponseLocation'] as $item) {
    echo $item['Address']['City'] . "\n";
}

收集所有城市到数组供后续使用

额外加了字段存在性判断,避免部分记录缺失对应字段时报错:

$response = curl_exec($ch);
$result = json_decode($response, true);
$allCities = [];

foreach ($result['GetLocationsResult']['ResponseLocation'] as $item) {
    if (isset($item['Address']['City'])) {
        $allCities[] = $item['Address']['City'];
    }
}

// 输出验证结果
print_r($allCities);

如果需要提取其他字段,直接在循环内获取$item下的对应键值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:54:03