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;
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']);