Json解码和阅读

时间:2016-11-14 00:10:27

标签: php json

我想创建一个脚本来共享GameServers统计信息。我正在使用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
]

或链接以测试它 HERE

我只读主机名。我尝试了太多muany方法,但它们对我不起作用。

3 个答案:

答案 0 :(得分: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']
?>

答案 1 :(得分: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
?>

答案 2 :(得分: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!