2016-11-14 72 views
0

我想制作脚本来共享GameServers统计信息。我正在使用JSON方法。我怎样才能读取主机名?Json解码和阅读

JSON

[ 
    [ 
     { 
      "ip": "176.57.188.22", 
      "port": "27022", 
      "rank": "1", 
      "online": "1", 
      "hostname": "..:: LS Public Server ::.. #1", 
      "num_players": "12", 
      "max_players": "32", 
      "location": "AL", 
      "mapa": "de_dust2" 
     } 
    ], 
    true 
] 

或连结测试LIVE HERE

我笏以只读的主机名。我尝试了很多方法,但他们不适合我。

回答

0

让我们假设JSON字符串(或对象)存储在变量$json中。

<?php 
// convert your JSON object to a PHP array 
$decoded_json = json_decode($json, true); 

print_r($decoded_json); // print your PHP array to check how to subindex your new var 
// I think it will be something like $decoded_json[0]['hostname'] 
?> 
0
<?php 
$test = '[ 
    [ 
     { 
      "ip": "176.57.188.22", 
      "port": "27022", 
      "rank": "1", 
      "online": "1", 
      "hostname": "..:: LS Public Server ::.. #1", 
      "num_players": "12", 
      "max_players": "32", 
      "location": "AL", 
      "mapa": "de_dust2" 
     } 
    ], 
    true 
]'; 
$test = json_decode($test); 
echo $test[0][0]->hostname; 
//---output--- 
//..:: LS Public Server ::.. #1 
?> 
0

使用json_decodetrue作为第二个参数,它给你一个关联数组,它会在JSON对象转换为PHP数组。

试试这个:

<?php 
error_reporting(0); 
$test = '[ 
    [ 
     { 
      "ip": "176.57.188.22", 
      "port": "27022", 
      "rank": "1", 
      "online": "1", 
      "hostname": "..:: LS Public Server ::.. #1", 
      "num_players": "12", 
      "max_players": "32", 
      "location": "AL", 
      "mapa": "de_dust2" 
     } 
    ], 
    true 
]'; 
$data = json_decode($test,true); 

foreach ($data as $info) { 
    foreach ($info as $result) { 
     echo $result[hostname]; 
    } 
} 

?> 

Demo!