我的PHP和json有什么问题

时间:2014-08-20 02:06:41

标签: php json

我想从我的json数组中得到一个响应:

stdClass Object ( [Foo] => stdClass Object ( [id] => 0001 [name] => Foo [profileIconId] => 550 [summonerLevel] => 30 [revisionDate] => 1408463933000 ) )

使用我当前的代码,我知道它很容易解决 - 但我不知道我做错了什么,因为我无法从我正在搜索的内容中找到与此相似的内容:< / p>

api.php:

<?php
class runeapi {
    const get_id_na = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
    const get_id_euw = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/';
    const key = '...';

    public function getID($summoner_name) {
        $name = $summoner_name;
        $call = self::get_id_euw .$name;
        return $this->request($call);
    }
    private function request($call) {
        $url = $call. '?api_key=' .self::key;
        $json = file_get_contents($url);
        $decode = json_decode($json);
        $result = $decode; //<-- This is the Issue.

        return $result;
    }
}
?>

testing.php:

<?php
include('api.php');
$summoner_name = 'Foo';

$test = new runeapi;
$r = $test->getID($summoner_name);

print_r($r);
?>

$r返回$result

我希望能够致电id,但无论我在哪里寻找,我都找不到类似于我的例子。

我尝试过的事情:

  • $decode->{'id'};

  • $decode{'id'};

2 个答案:

答案 0 :(得分:1)

我相信这对你有用

private function request($call) {
        $url = $call. '?api_key=' .self::key;
        $json = file_get_contents($url);

        return $json;
    } 

无需解码。

答案 1 :(得分:0)

我必须将另一个变量添加到request()

public function getID($summoner_name) {
    $name = $summoner_name;
    $call = self::get_id_euw .$name;
    return $this->request($call, $name); //<-- added $name
}
private function request($call, $name) { //<-- added $name
    $url = $call. '?api_key=' .self::key;
    $json = file_get_contents($url);
    $decode = json_decode($json);
    $result = $decode->{$name}->{'id'}; //<-- added $name

    return $result;
}