在 PHP 中访问 JSON 对象名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1479033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:45:18  来源:igfitidea点击:

Access JSON object name in PHP

phpjson

提问by xadoc

I have the following 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
    }
  }
}

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

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

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

回答by Peter Bailey

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

我想最简单的事情是解码成关联数组而不是 stdClass 对象

$obj2 = json_decode( $json, true );

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

回答by Pascal MARTIN

Considering this piece of code :

考虑这段代码:

$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}}}';
$obj2 = json_decode($json);
var_dump($obj2);

You'll get :

你会得到 :

object(stdClass)[1]
  public 'nickname' => string 'xadoc' (length=5)
  public 'level' => int 4
  public 'loc' => string 'Tulsa, OK, USA' (length=14)
  public 'score' => int 122597
  public 'money' => float 29412.5
  public 'streetNum' => int 8
  public 'streets' => 
    object(stdClass)[2]
      public '-91607259/387798111' => 
        object(stdClass)[3]
          public 'name' => string 'Alaméda António Sérgio' (length=25)
          public 'value' => int 243
          public 'type' => int 1
      public '-91016823/388182402' => 
        object(stdClass)[4]
          public 'name' => string 'Autoestrada do Norte' (length=20)
          public 'value' => int 18304
          public 'type' => int 1
      public '-86897820/399032795' => 
        object(stdClass)[5]
          public 'name' => string 'Autoestrada do Norte' (length=20)
          public 'value' => int 12673
          public 'type' => int 1
      public '-973092846/479475465' => 
        object(stdClass)[6]
          public 'name' => string '19th Ave' (length=8)
          public 'value' => int 7794
          public 'type' => int 1
      public '-974473223/480054888' => 
        object(stdClass)[7]
          public 'name' => string '23rd Ave NE' (length=11)
          public 'value' => int 33977
          public 'type' => int 1

Which means you can loop over the streets like this :

这意味着你可以像这样在街道上循环:

foreach ( $obj2->streets as $id => $street ) {
    echo $id;
    var_dump($street);
    echo '<hr />';
}

With this, for each $street, you'll get the corresponding key into $id-- and the data into $street.

这样,对于每个$street,您将获得相应的键$id- 并将数据放入$street.


Or you can directly access one this way :


或者您可以通过这种方式直接访问一个:

$street = $obj2->streets->{'-86897820/399032795'};
var_dump($street);

Which will get you :

这会让你:

object(stdClass)[5]
  public 'name' => string 'Autoestrada do Norte' (length=20)
  public 'value' => int 12673
  public 'type' => int 1


Your $obj2->streetis an object, which means you cannot use array-syntax access ; this explains the "Fatal error: Cannot use object of type stdClass as array" if you try to use this :


$obj2->street是一个对象,这意味着你不能使用数组语法访问;这解释了“ Fatal error: Cannot use object of type stdClass as array”,如果您尝试使用它:

$obj2->streets['-86897820/399032795'];

But the properties of your object have quite "strange" names ; which means you cannot do this :

但是你的对象的属性有很“奇怪”的名字;这意味着你不能这样做:

$obj2->streets->-86897820/399032795;

Which gives Parse error: syntax error, unexpected '-', expecting T_STRING or T_VARIABLE or '{' or '$'

这使 Parse error: syntax error, unexpected '-', expecting T_STRING or T_VARIABLE or '{' or '$'

Nor that :

也不是:

$obj2->streets->'-86897820/399032795';

Which also gives Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_STRING or T_VARIABLE or '{' or '$'

这也给 Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_STRING or T_VARIABLE or '{' or '$'

Happily, you can use {}to kind of "protect" the name of your keys, and get everything working ;-)
(I cannot find the page in the manual that explains this syntax nor give its name... If anyone know... )

令人高兴的是,您可以使用{}来“保护”您的密钥名称,并使一切正常;-)
(我在手册中找不到解释此语法的页面,也找不到其名称...如果有人知道... )

回答by Hamid Araghi

A simple way to extract data from Json stringis to use jsone_decode()function. For example:

从中提取数据的一种简单方法Json string是使用jsone_decode()函数。例如:

$json_data = '{"nickname":"xadoc","level":4,"loc":"Tulsa}';
$decoded_data = json_decode($json_data);

Then you can simply access the members of $decoded_datausing ->operator:

然后您可以简单地访问$decoded_datausing->运算符的成员:

echo "$decoded_data->nickname \n";
echo "$decoded_data->level \n";

And if your extracted members from $decoded_dataare json strings again, then you can use json_decode()again!

如果您从$decoded_data中提取的成员json string再次是s,那么您可以json_decode()再次使用!

回答by jeroen

I can′t try it right now, but if you do a:

我现在不能尝试,但如果你做:

var_dump($obj2);

you should be able to see exactly how to access your information.

您应该能够准确了解如何访问您的信息。