仅基于某些主机解析JSON数据

时间:2016-06-06 14:15:18

标签: php json

{
"0000": {
    "Host":"example1",
    "Port":50001,
    "Proto":"tcp",
    "UTXO Root":"c7cf1881",
    "Height":415072,
    "Blocktime":"2016-06-06 14:07:41",
    "Version":"1.0\/j\/beancurd",
    "Connection":"open",
    "ConnectionTime":"2016-06-06 13:40:58",
    "Status":"OK",
    "Uptime Hour Day Month":"1.0000 1.0000 0.9982"
},
"0001" : {
    "Host":"example2.com",
    "Port":50002,
    "Proto":"ssl",
    "UTXO Root":"c7cf1881",
    "Height":415072,
    "Blocktime":"2016-06-06 14:07:41",
    "Version":"1.0\/j\/beancurd",
    "Connection":"open",
    "ConnectionTime":"2016-06-06 13:40:52",
    "Status":"OK",
    "Uptime Hour Day Month":"1.0000 1.0000 0.9996"
}

在这个json文件中,我想获得一个仅基于HOST和PHP的数据状态,例如我想获得主机example2的状态。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我要做的第一件事就是json_decode(),当然,我可以将它用作PHP数组。接下来的事情是使用if-else语句在数组中查找主机。最后,如果找到匹配,我会得到状态。像这样:

<?php
// supposing the the host to look for is saved in $host

$array = json_decode($json, true);
foreach($array as $k => $object){
    if($host == $object['Host']){
        $status = $object['Status'];
        break; // the break is to stop foreach saving time and resources.
    }
}

答案 1 :(得分:0)

$records = json_decode($jsonString, true);

$requiredRecord = [];
foreach ($records as $record) {
  if ($record['Host'] == 'example2.com') {
    $requiredRecord = $record;
    break;
  }
}

这样的东西?