2015-06-08 144 views
0

我想在我的網站中使用一些JSON數據,但是我試圖讀取時卡住了。通過相對路徑通過多維PHP數組導航

獲取數據運行良好:

<?php 
 
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')); 
 
?>

這是JSON數據的一個小片段,但它持續了問題的解釋

{ 
 
    "type": "champion", 
 
    "format": "standAloneComplex", 
 
    "version": "5.10.1", 
 
    "data": { 
 
     "Aatrox": { 
 
      "version": "5.10.1", 
 
      "id": "Aatrox", 
 
      "key": "266", 
 
      "name": "Aatrox", 
 
      "title": "Die Klinge der Düsteren", 
 
      "info": { 
 
       "attack": 8, 
 
       "defense": 4, 
 
       "magic": 3, 
 
       "difficulty": 4 
 
      }, 
 
     }, 
 
     "Ahri": { 
 
      "version": "5.10.1", 
 
      "id": "Ahri", 
 
      "key": "103", 
 
      "name": "Ahri", 
 
      "title": "Die neunschwänzige Füchsin", 
 
      "info": { 
 
       "attack": 3, 
 
       "defense": 4, 
 
       "magic": 8, 
 
       "difficulty": 5 
 
      }, 
 
     }, 
 
    } 
 
}

問題:如何在不知道「標題」的情況下訪問「鍵」的值(例如, 「Aatrox」)? 我試過$ data - > {'data'} [0] - > {'key'},但這不起作用。

第二個問題:我也嘗試搜索「key」的值,但在PHP中使用此方法構建路徑時沒有成功。 JavaScript的嘗試運行良好,但我寧願有一個服務器端的解決方案。 感謝您的幫助!

+2

遍歷,直到你找到你想要的元素'$數據 - >數據$關鍵=> $ value'。 – deceze

+0

'foreach($ array as $ key => $ value)',基本上。 –

+0

您認爲如何區分Aatrox.key和Ahri.key?或者你對所有的價值感興趣 – splash58

回答

0

如果你想在特定的 '抵消' 的元素,使用

array_values($data->data)[0]->key; 

否則,使用的foreach:

foreach ($data->data as $heading=>$data) { 
    echo "The heading is $heading and key is {$data->key}"; 
} 
-1

個人而言,我更喜歡JSON對象轉換成更多的PHP友好的陣列。

如果使用json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'))); 您可以用什麼來訪問鍵值這樣

$champions = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'))); 

foreach($champions['data'] as $key => $row){ 
    echo $row['key']; 
} 

這會呼應你的鑰匙。

0

另類很短的方式:

<?php 
    $data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'), true); 
    $first = current($data['data']); 

更完整的例子:

<?php 
    $data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')); 
    $key = current($data->data)->key