R. Rio R. Rio - 7 months ago 26
PHP Question

Obtain the first entry of 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;

Answer

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)
}