获取JSON的第一个条目
I have this JSON in a URL:
{"success":true,"rgInventory":{"6073259621":{"id":"6073259621","classid":"1660549198","instanceid":"188530139","amount":"1","pos":1}}}
I need obtain the first entry after rgInventory
. The problem is the problem is that suppose that I don't know that there are "6073259621"
. How I can obtain it without know what there?
I try this but don't work:
$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;
我在URL中有这个JSON: p>
{“ 成功 “:真实的,” rgInventory “:{” 6073259621 “:{” ID “:” 6073259621" , “CLASSID”: “1660549198”, “实例id”: “188530139”, “量”: “1”, “POS” :1}}}
code> pre>
我需要在 rgInventory code>之后获取第一个条目。 问题是问题是假设我不知道有“6073259621” code>。 我怎么能在不知道是什么的情况下获得呢? p>
我试试这个但不起作用: p>
$ 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;
code> pre>
div>
Here's a simple way to get the key and the value (array) using each():
$data = json_decode(file_get_contents($url), true);
list($key, $val) = each($data['rgInventory']);
echo $key;
print_r($val);
Yields:
6073259621
Array
(
[id] => 6073259621
[classid] => 1660549198
[instanceid] => 188530139
[amount] => 1
[pos] => 1
)
But I just noticed that the id
is the same as the key, so not really needed.
if the JSON string is valid and like below
{ "success":true,
"rgInventory":{
"6073259621":{
"id":"6073259621",
"classid":"1660549198",
"instanceid":"188530139",
"amount":"1",
"pos":1
}
}
}
get the decode in $obj like
$obj = json_decode(file_get_contents($url), true);
then your first entry would be
echo array_keys($obj['rgInventory'])[0];
to understand it clearly and to know where is "6073259621"
$obj = json_decode(file_get_contents($url), true);
var_dump($obj);
also note the difference
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
the output would be ..
// 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)
}
After you have the JSON decoded with this:
$obj = json_decode(file_get_contents($url), true);
You can get the first item from rgInventory
, regardless of what its key is, using reset
.
$first_entry = reset($obj['rgInventory']);