解码JSON PHP

时间:2014-01-26 09:49:30

标签: php json

我正在尝试使用JSON解码,但我无法读取节点结果。

    <html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$request =  'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDMXN%22%2C%20%22USDCHF%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=';
$session = curl_init($request);  
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);     
$obj = json_decode($json, true);
if(!is_null($obj->query->results)){
  // Safe to parse datae
  echo results .'</br>';
}

print_r( $obj['results']);

?>
</body>
</html>

JSON

 {
 "query": {
  "count": 2,
  "created": "2014-01-26T01:20:15Z",
  "lang": "en-US",
  "diagnostics": {
   "user-time": "259",
   "service-time": "341",
   "build-version": "0.2.2157"
  },
  **"results": {**
   "rate": [
    {
     "id": "USDMXN",
     "Name": "USD to MXN",
     "Rate": "13.4525",
     "Date": "1/25/2014",
     "Time": "7:20am",
     "Ask": "13.453",
     "Bid": "13.452"
    },
    {
     "id": "USDCHF",
     "Name": "USD to CHF",
     "Rate": "0.8945",
     "Date": "1/25/2014",
     "Time": "7:20am",
     "Ask": "0.8947",
     "Bid": "0.8943"
    }
   ]
  }
 }
}

我正在尝试获取节点“结果”,以便我可以获得可用于在网站中显示的货币汇率。

此代码使用yahoo api获取货币转换率。

2 个答案:

答案 0 :(得分:0)

由于您在json_decode中使用true作为参数,因此您将得到一个数组。

尝试

 if(!is_null($obj['results']['rate'])){
     foreach($obj['results']['rate'] as $value){
      echo "{$value['Name']} => {$value['Rate']}<br>";
     }
 }

答案 1 :(得分:-1)

您必须使用$obj->results,因为它与查询处于同一级别。