2015-06-08 59 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