【发布时间】:2018-02-28 01:38:47
【问题描述】:
我正在从一个 JSON API 中获取 Pokemon 数据,它显示任何 Pokemon 的值。这里的目的是获取数据,显示可以在哪些游戏中找到口袋妖怪,以及在游戏中的哪些区域找到它们。
https://pokeapi.co/api/v2/pokemon/183/
这是通过其encounters 键值访问的。我对通过以下方式访问特别感兴趣:
['location_area']['name'] 和 ['version']['name']
作为一个很好的 URL 示例:https://pokeapi.co/api/v2/pokemon/183/encounters
问题是,遇到数组索引值是一个 URL,我通过我自己的 Curl json 函数访问它,它工作正常,但只会给我数组数字索引值。
public function getPokemonLocation($searchTerm)
{
/*
Get the Pokemon via search term name
*/
$url = $this->baseUrl.$searchTerm;
$pokemonLocation = $this->getUrl($url);
/*
$pokemonLocationUrl is the encounters subset i the array URL
*/
$pokemonLocationUrl = $pokemonLocation['location_area_encounters'];
$pokemonLocationEncounters = $this->getUrl('https://pokeapi.co/' . $pokemonLocationUrl);
echo "<pre>";
print_r($pokemonLocationEncounters);
echo "</pre>";
/*
Now grab the data needed from the name of location and what game regions they are from
*/
$pokemonAreaEncounterArea = array();
$pokemonAreaEncounterGame = array();
foreach($pokemonLocationEncounters as $key => $encounter)
{
$pokemonAreaEncounterArea[] = $encounter['location_area']['name'];
$pokemonAreaEncounterGame[] = $encounter['version_details'][0]['version']['name'];
}
$pokemonLocationAndRegion = array_combine($pokemonAreaEncounterGame,$pokemonAreaEncounterArea);
// print_r($pokemonLocationAndRegion);
return $pokemonLocationAndRegion;
}
问题是,遇到数组索引值是一个 URL,我通过我自己的 Curl json 函数访问它,它工作正常,但只会给我数组数字索引值。
我可以轻松获取数据,如上图。但是,我们希望完全访问所有数组索引,而不仅仅是一个或少数数据。很想通过多个 foreach 来做到这一点,但宁愿干净地实现它。
编辑:这是上面 Poke APi 链接的第二个示例,如果您收到 504 服务器错误 - https://jsoneditoronline.org/?id=73911ec678c850f9b1ff131ac7ee738c
【问题讨论】:
-
pokeapi.co 给出 504 错误。你能提供一个json数据的样本吗?
-
@Cemal,当然我想这个链接应该足够了,jsoneditoronline.org/?id=73911ec678c850f9b1ff131ac7ee738c
-
这个
$this->getUrl($url);返回(json_decoded)数组还是json? -
与您目前得到的结果相比,您的预期结果是什么?
-
@Cemal - 是的,它通过 json_decode() 返回一个 json 数组