gpt4 book ai didi

php - 在 PHP 中访问 JSON 对象名称

转载 作者:可可西里 更新时间:2023-10-31 22:19:11 25 4
gpt4 key购买 nike

我有以下 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>';
}

最佳答案

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

$obj2 = json_decode( $json, true );

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

关于php - 在 PHP 中访问 JSON 对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1479033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com