drpogkqqi536984960
2014-12-19 15:53
浏览 145

从json格式中提取特定数据

I have the following json format data :

{"query":{
  "count":5,"created":"2014-12-19T15:42:41Z","lang":"en-US","results":{
    "channel":[{
      "item":{
        "forecast":{"date":"19 Dec 2014","high":"61","low":"47"}
       }},{
      "item":{
        "forecast":{"date":"20 Dec 2014","high":"60","low":"48"}
       }},{
      "item":{
        "forecast":{"date":"21 Dec 2014","high":"61","low":"44"}
       }},{
      "item":{
        "forecast":{"date":"22 Dec 2014","high":"58","low":"46"}
       }},{
      "item":{
        "forecast":{"date":"23 Dec 2014","high":"58","low":"45"}
       }}]
     }
   }
}

How can I access specific data from this format (for example only high and low), in order to insert these data in a mySQL database for instance?

图片转代码服务由CSDN问答提供 功能建议

我有以下json格式数据:

  {“ 查询“:{
”count“:5,”created“:”2014-12-19T15:42:41Z“,”lang“:”en-US“,”results“:{
”channel“:[  {
“item”:{
“forecast”:{“date”:“2014年12月19日”,“高”:“61”,“低”:“47”} 
}},{
“ 项目“:{
”预测“:{”日期“:”2014年12月20日“,”高“:”60“,”低“:”48“} 
}},{
”item“:{  
“预测”:{“日期”:“2014年12月21日”,“高”:“61”,“低”:“44”} 
}},{
“item”:{
“预测 “:{”date“:”2014年12月22日“,”高“:”58“,”低“:”46“} 
}},{
”item“:{
”forecast“:{”  date“:”2014年12月23日“,”“高”:“58”,“低”:“45”} 
}}] 
} 
} 
} 
   \  n 
 

如何从这种格式访问特定数据(例如只有高和低),以便将这些数据插入到mySQL数据库中?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dskvfdxgdo2422392 2014-12-19 16:17
    已采纳

    Put your json in a variable $str for example, than you can access the items :

    $json = json_decode($str);
    $res = $json->{'query'}->{'results'}->{'channel'};
    foreach($res as $ch) {
        echo "High:" . $ch->{'item'}->{'forecast'}->{'high'} . "<br>";
        echo "Low:" . $ch->{'item'}->{'forecast'}->{'low'} . "<br>";
    }
    
    打赏 评论
  • duanjuan3931 2014-12-19 15:58

    Use json_decode to turn it into an array:

    $array = json_decode($json_data, true);
    

    Then, you can access the items, forecast, and high/low values:

    $high = $array[1]['item']['forecast']['high'];
    
    打赏 评论
  • dongyan3853 2014-12-19 15:59

    Assuming your json string is the variable $json:

    $data = json_decode($json);
    $channels = $data->query->results->channel;
    foreach($channels as $channel) {
        // DO SOMETHING HERE
        die($channel["item"]["high"]);
    }
    
    打赏 评论

相关推荐 更多相似问题