How to use foreach with this type of JSON (PHP)

1

I'm trying to display the values of a JSON with PHP most unsuccessfully. Used Code:

JSON

{
    "friendslist": {
        "friends": [
            {
                "steamid": "76561197960265731",
                "relationship": "friend",
                "friend_since": 0
            },
            {
                "steamid": "76561197960265738",
                "relationship": "friend",
                "friend_since": 0
            },
            {
                "steamid": "76561197960265740",
                "relationship": "friend",
                "friend_since": 0
            },
            {
                "steamid": "76561197960265747",
                "relationship": "friend",
                "friend_since": 0
            }
        ]
    }
}
PHP
$steamid_player = "76561198112612121";
        $apikey = "APIKEY";

       $amg = file_get_contents("http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=$apikey&steamid=$steamid_player&relationship=friend");
        $decode = json_decode($amg, TRUE);

        foreach ($decode["friendslist"]["friends"][0] as $valor){

            $steamid = $valor["relationship"]->steamid;

            echo $steamid;
        }

Error returned


Warning: Illegal string offset 'relationship' in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\leo\test.php on line 10

Notice: Trying to get property of non-object in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\leo\test.php on line 10

Warning: Illegal string offset 'relationship' in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\leo\test.php on line 10

Notice: Trying to get property of non-object in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\leo\test.php on line 10

Notice: Trying to get property of non-object in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\leo\test.php on line 10

But an error is always returned, so no value is displayed. Where am I going wrong?

    
asked by anonymous 29.12.2015 / 20:53

1 answer

5

Here's a simplification, and syntax correction:

$decode = json_decode( $amg, TRUE );
foreach ( $decode["friendslist"]["friends"] as $valor){
    $steamid = $valor["steamid"];
    echo $steamid;
}

See working at IDEONE .

You were calling the index [0] in foreach , and it already goes to $valor . In addition, I was treating the return as an object, with json_decode returning associative array.


Object version

See the syntax difference by changing TRUE from json_decode() :

$decode = json_decode( $amg, FALSE );
foreach ( $decode->friendslist->friends as $valor){
    $steamid = $valor->steamid;
    echo $steamid;
}

Here you also have a demo at IDEONE .

The second parameter of json_decode just determines whether the return will be an associative array or array .

    
29.12.2015 / 21:02