我收到的JSON响应如下:
stdClass Object
(
[location00] => Array
(
[0] => stdClass Object
(
[id_0] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Wanted by Aryurumoka
[gold_reward] => 58900
[event] => 0
[description] => Not provided.
)
)
)
)
)
例如,我可以[name]
获得$quests->location00[0]->id_0[0]->name
。
假设我创建了一个新变量$location = 'location00'
。现在,如果我尝试$quests->$location[0]->id_0[0]->name'
,我会收到Undefined property: stdClass::$l
错误。我也试过了$location = 'location00[0]'
但是我完全不知道为什么会这样。如何在解析JSON时将location00
分配给变量以使用它?
答案 0 :(得分:2)
您可以使用关联数组或$ obj-> {$ var}:
<?php
$quests = json_decode($json, true);
$location = 'location00';
$name = $quests[$location][0]['id_0'][0]['name'];
答案 1 :(得分:1)
我尝试获取新的JSON,但您可以使用大括号插入对象属性检索:
$quests->{$location}[0]