小编典典

在PHP中访问JSON对象名称

json

我有以下JSON:

{
  "nickname": "xadoc",
  "level": 4,
  "loc": "Tulsa, OK, USA",
  "score": 122597,
  "money": 29412.5,
  "streetNum": 8,
  "streets": {
    "-91607259\/387798111": {
      "name": "Alam\u00e9da Ant\u00f3nio S\u00e9rgio",
      "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
    }
  }
}

我拼命尝试访问动态对象名称,如"-91607259\/387798111",该怎么办?

现在我有:

$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>';
}

阅读 316

收藏
2020-07-27

共1个答案

小编典典

我可以想象,最简单的方法是解码为关联数组而不是stdClass对象

$obj2 = json_decode( $json, true );

foreach ( $obj2['streets'] as $coords => $street )
{   
  echo $coords;
}
2020-07-27