【问题标题】:How to access properties of a nested PHP object?如何访问嵌套 PHP 对象的属性?
【发布时间】:2015-02-01 20:57:27
【问题描述】:

我正在尝试做一个网络应用程序,人们可以看到他们在英雄联盟中的状态,但我什至不知道如何做一些事情。
我有这门课:

stdClass Object
(
    [player] => stdClass Object
        (
            [id] => xxxxxx
            [name] => yyyy
            [profileIconId] => 627
            [summonerLevel] => 30
            [revisionDate] => 1422798145000
        )
 )

我正在使用这个 php 代码:

<?php 
        $summoner = 'yohanbdo';
        $summonerdata = $leagueclass->getsummoner($summoner);
      ?>

我只想获取 id、name 和 profileIconId 并显示它。我不知道该怎么做。
PD:我的英语不太好,谢谢大家的编辑。

【问题讨论】:

标签: php json stdclass


【解决方案1】:

奇怪,我刚才还在看 Riot API。

我觉得你对这种类型的符号很陌生,所以我会尽量快速但简洁地解释我的解释。

正如 Gerifield 所说,你所拥有的是对象。您可以使用-&gt; 运算符访问它们的属性。例如,如果我假设对象 $main 就是你的 var_dumping ,那么你可以简单地像这样获取对象:

$main = json_decode($some_json_string);
//Now that we have the object set, we can deal with the properties.
echo $main->player->name; 
//This will output the player name. 
echo $main->player->id;
//Will output the player ID.

请注意,由于$main 对象的player也是一个对象,因此必须通过-&gt; 运算符访问它的属性。

但是,您也可以通过将第二个参数传递给 json_decode 来简单地使用关联数组,如下所示:

$main = json_decode($some_json_string,TRUE);
echo $main['player']['id'];
echo $main['player']['name'];

希望这会有所帮助。

【讨论】:

  • 谢谢亲爱的回答,但我做不到。我实际上使用的是harings.be/lolclass,而不是官方的 Riot API。你能加我一个Skype吗?只需 5 分钟。用户:“wesley.bdo”。如果你不能,无论如何,谢谢。
  • 对不起,我不使用 Skype。
猜你喜欢
  • 2016-07-13
  • 2012-11-12
  • 2021-03-12
  • 2015-02-08
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
相关资源
最近更新 更多