在PHP中访问JSON对象名称 [英] Access JSON object name in PHP

查看:107
本文介绍了在PHP中访问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"这样的动态对象名称,该怎么办?

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

现在我有:

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

推荐答案

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

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

这篇关于在PHP中访问JSON对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆