PHP读取json数据
我对PHP和web编程一无所知。我正在尝试从steam API读取一些json数据 数据: 我设法找到了单个对象(我相信?) 这是我的代码:PHP读取json数据,php,json,api,steam,Php,Json,Api,Steam,我对PHP和web编程一无所知。我正在尝试从steam API读取一些json数据 数据: 我设法找到了单个对象(我相信?) 这是我的代码: <?php $url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X'; $JSON = file_get_contents($url); $data = json_decode($JSON); $heroes = reset(
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
我的意思是,数组键应该是id,值应该是英雄的名字
另外,我将heroes变量设置为reset(
reset($data)
)的where似乎不是我想要的方法,也许有更好的方法?您可以使用array\u map()
函数在两个单独的数组中提取id和名称,然后使用array\u combine()
从先前提取的数组创建键值对数组
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
您可以使用
array\u map()
函数在两个单独的数组中提取id和名称,然后使用array\u combine()
从先前提取的数组中创建键值对数组
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
一个更简单更明显的解决方案是简单地循环通过它。从你的粘贴库中,我看到你的数据被包装在两个级别的数组中,所以
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(无需执行任何reset
调用;获取数组的第一个元素是一种奇怪的方式)
注意,要使其工作,您必须应用@RamRaider提供的提示
$data = json_decode($JSON, true);
为了让
json\u decode
返回数组,而不是StdClass。一个更简单更明显的解决方案是简单地循环通过它。从你的粘贴库中,我看到你的数据被包装在两个级别的数组中,所以
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(无需执行任何reset
调用;获取数组的第一个元素是一种奇怪的方式)
注意,要使其工作,您必须应用@RamRaider提供的提示
$data = json_decode($JSON, true);
为了让json_decode
返回数组,而不是StdClass。可能重复的json_decode($data)将生成一个对象(StdClass),而json_decode($data,true)将生成一个数组。可能重复的json_decode($data,true)将生成一个对象(StdClass),而json_decode($data,true)将生成一个数组。