2016-11-14 67 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!