我在URL中有这个JSON:
{"success":true,"rgInventory":{"6073259621":{"id":"6073259621","classid":"1660549198","instanceid":"188530139","amount":"1","pos":1}}}
我需要获得rgInventory
之后的第一个条目。问题是,假设我不知道有"6073259621"
。我怎么能在不知道那里有什么的情况下获得它?
我尝试了这个,但不起作用:
$obj = json_decode(file_get_contents($url), true);
$obj2 = json_decode(json_encode($obj['rgInventory']), true);
$obj3 = json_decode(json_encode($obj2), true);
echo $obj3;
以下是使用each()获取键和值(数组)的简单方法:
$data = json_decode(file_get_contents($url), true);
list($key, $val) = each($data['rgInventory']);
echo $key;
print_r($val);
收益率:
6073259621
Array
(
[id] => 6073259621
[classid] => 1660549198
[instanceid] => 188530139
[amount] => 1
[pos] => 1
)
但我只是注意到id
和密钥是一样的,所以不是真的需要。
使用以下内容解码JSON后:
$obj = json_decode(file_get_contents($url), true);
您可以使用reset
从rgInventory
获取第一个项目,而不管它的密钥是什么。
$first_entry = reset($obj['rgInventory']);
如果JSON字符串有效并且类似于
{ "success":true,
"rgInventory":{
"6073259621":{
"id":"6073259621",
"classid":"1660549198",
"instanceid":"188530139",
"amount":"1",
"pos":1
}
}
}
像一样在$obj中获得解码
$obj = json_decode(file_get_contents($url), true);
那么你的第一个条目将是
echo array_keys($obj['rgInventory'])[0];
清楚地理解它并知道"6073259621"在哪里
$obj = json_decode(file_get_contents($url), true);
var_dump($obj);
还要注意的差异
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
输出将为。。
// decode as object
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
// decode as array
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}