【问题标题】:PHP reading json dataPHP读取json数据
【发布时间】:2015-12-27 00:40:28
【问题描述】:

我完全是 PHP 和网络编程新手。我正在尝试从 Steam API 读取一些 json 数据。

数据:http://pastebin.com/hVWyLrfZ

我设法找到了单个对象(我相信?)。

这是我的代码:

<?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 => name

我的意思是,数组键应该是 id,值应该是英雄名称。

另外,我将 hero 变量设置为 reset(reset($data)) 似乎是做我想做的事情的坏方法,也许有更好的方法?

【问题讨论】:

  • json_decode to array的可能重复
  • json_decode( $data ) 将产生一个对象 (stdClass) 而 json_decde($data,true) 将产生一个数组。

标签: php json api steam


【解决方案1】:

您可以使用array_map() 函数在两个单独的数组中提取id 和名称,然后使用array_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);

【讨论】:

    【解决方案2】:

    一个更简单更明显的解决方案是简单地循环它。从您的 pastebin 中,我看到您的数据包含在两级数组中,所以 ...

    $myResult = [];
    foreach ($data['result']['heroes'] as $nameId) {
        $myResult[$nameId['id']] = $nameId['name'];
    }
    

    (无需进行任何reset 调用;这是获取数组第一个元素的一种奇怪方式)

    注意,要使此功能起作用,您必须应用@RamRaider 的提示

    $data = json_decode($JSON, true);
    

    为了让json_decode 返回数组,而不是 StdClass。

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2016-04-01
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多