Skip to content
Advertisement

Access JSON object name in PHP

I have the following JSON:

{
  "nickname": "xadoc",
  "level": 4,
  "loc": "Tulsa, OK, USA",
  "score": 122597,
  "money": 29412.5,
  "streetNum": 8,
  "streets": {
    "-91607259/387798111": {
      "name": "Alamu00e9da Antu00f3nio Su00e9rgio",
      "value": 243,
      "type": 1
    },
    "-91016823/388182402": {
      "name": "Autoestrada do Norte",
      "value": 18304,
      "type": 1
    },
    "-86897820/399032795": {
      "name": "Autoestrada do Norte",
      "value": 12673,
      "type": 1
    },
    "-973092846/479475465": {
      "name": "19th Ave",
      "value": 7794,
      "type": 1
    },
    "-974473223/480054888": {
      "name": "23rd Ave NE",
      "value": 33977,
      "type": 1
    }
  }
}

I’m desperately trying to access the dynamic object names like "-91607259/387798111", how can I do it?

Right now I have:

$jsonurl = "http://www.monopolycitystreets.com/player/stats?nickname=$username&page=1";
$json = file_get_contents($jsonurl,0,null,    $obj2 = json_decode($json);

foreach ( $obj2->streets as $street )
{   
    //Here I want to print the "-91607259/387798111" for each street, please help
    //echo $street[0]; gives "Fatal error: Cannot use object of type stdClass as array"
    //echo $street gives "Catchable fatal error: Object of class stdClass could not be converted to string"
    echo '<th>'.$street->name.'</th><td>'."M ".number_format($street->value, 3, ',', ',').'</td>';
}

Advertisement

Answer

I would imagine that the simplest thing to do is to decode into associative arrays instead of stdClass objects

$obj2 = json_decode( $json, true );

foreach ( $obj2['streets'] as $coords => $street )
{   
  echo $coords;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement