按值获取stdClass对象

时间:2013-10-21 00:19:09

标签: php key stdclass

鉴于此stdClass结构......

[RecentAchievements] => stdClass Object
    (
        [1446] => stdClass Object
           (
               [3319] => stdClass Object
                   (
                       [ID] => 3319
                       [GameID] => 1446
                       [Title] => Hello World!
                       [Description] => Complete World 1-1
                       [Points] => 15
                       [BadgeName] => 03909
                       [IsAwarded] => 1
                       [DateAwarded] => 2013-10-20 19:35:46
                   )

我需要检查3319内的对象,比如“Title”,所以它就像是:

$data->RecentAchievements->$gameid->ACHVIDHERE->Title;

要获得$ gameid,它来自其他对象(RecentPlayed),这样:

[RecentlyPlayed] => Array
    (
        [0] => stdClass Object
            (
                [GameID] => 1446
                [ConsoleID] => 7
                [ConsoleName] => NES
                [Title] => Super Mario Bros
                [LastPlayed] => 2013-10-20 21:38:22
                [ImageIcon] => /Images/000385.png
                [ImageTitle] => /Images/000272.png
                [ImageIngame] => /Images/000387.png
                [ImageBoxArt] => /Images/000275.png
            )

    )

$gameid = $data3->RecentlyPlayed['0']->GameID;

API不允许我使用相同的RecentPlayed来获取成就ID,我必须从RecentAchievements中提取它。有可能吗?

2 个答案:

答案 0 :(得分:4)

如果你刚刚完成特定游戏的第一个成就,你可以使用这个黑客:

$firstAchievement = reset($data->RecentAchievements->$gameid);
$title = $firstAchievement->Title;

API可能会给你一个JSON响应,所以你可能还想考虑这个:

$data = json_decode($response, true);
                               ^^^^

第二个参数true将JavaScript对象转换为PHP数组,这在大多数情况下使得处理它们变得更容易,例如。

$firstAchievement = reset($data['RecentAchievements'][$gameid]);
$title = $firstAchievement['Title'];

答案 1 :(得分:1)

您可以使用复杂的卷曲符号来引用对象的动态属性

$data->RecentAchievements->{$gameid}->{$someotherid}->Title;

这应该为您Hello World!提供$gameid == 1446$someotherid == 3319