如何用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
相关产品推荐
相关产品推荐

