Search code examples
phpkeystdclass

Get stdClass Object by value


Given this stdClass structure...

[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
                   )

I need to check the objects inside 3319, like "Title", so it'd be like:

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

To get the $gameid, it came from other object (RecentlyPlayed), this way:

[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 don't let me use the same RecentlyPlayed to get the achievement ID, i have to extract it from RecentAchievements. Is it possible?


Solution

  • If you're just after the first achievement for that particular game, you could use this hack:

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

    The API is probably giving you a JSON response, so you may also want to consider this:

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

    The second parameter true turns the JavaScript objects into PHP arrays, which in most cases makes it easier to handle them, e.g.

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