2016-05-10 4 views
0

の最初のエントリの取得:私はrgInventory後の最初のエントリを取得する必要がある私はURLでこのJSONを持つJSON

{"success":true,"rgInventory":{"6073259621":{"id":"6073259621","classid":"1660549198","instanceid":"188530139","amount":"1","pos":1}}} 

を。問題は、私が"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; 
+1

'array_keys()'でキーを取得し、最初のキーを取得してキーを取得します。 – Rizier123

+1

複数回デコードする必要はありません。初めてデコードしたら、配列を持ち歩くことができます。 –

+0

実際に '6073259621'やそれに含まれる配列を返そうとしていますか? – AbraCadaver

答えて

0

ここeach()を使用してキーと値(配列)を取得する簡単な方法です

6073259621 
Array 
(
    [id] => 6073259621 
    [classid] => 1660549198 
    [instanceid] => 188530139 
    [amount] => 1 
    [pos] => 1 
) 

しかし、私はちょうどidが同じであることに気づきましたキーとして、本当に必要なわけではありません。

0

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

$obj = json_decode(file_get_contents($url), true); 
var_dump($obj); 

も違いに注意明確にそれを理解すると "6073259621" である場所を知ることであろう

あなたは関係なく、そのキーが何であるかの、 rgInventoryから最初の項目を取得することができます

$obj = json_decode(file_get_contents($url), true); 

:あなたはこれでJSONをデコードした後0

出力は...

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

だろうresetを使用してください。

$data = json_decode(file_get_contents($url), true); 

list($key, $val) = each($data['rgInventory']); 

echo $key; 
print_r($val); 

収量:

$first_entry = reset($obj['rgInventory']); 
関連する問題