2016-05-10 14 views
0

的第一個條目我有這個JSON的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; 
+1

使用'array_keys()'獲取密鑰以及獲取第一個密鑰然後獲得密鑰的用法。 – Rizier123

+1

無需多次解碼。一旦你第一次解碼你將有一個數組,你可以遍歷。 –

+0

你確實想返回6073259621或它所包含的數組嗎? – AbraCadaver

回答

0

這裏有一個簡單的方法來獲得使用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是相同的作爲關鍵,所以不是真的需要。

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

清楚地瞭解它,知道哪裏是 「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) 
} 
0

在您的JSON解碼與此:

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

您可以從rgInventory得到第一個項目,不管它的關鍵是什麼,使用reset

$first_entry = reset($obj['rgInventory']);