从json格式中提取特定数据

时间:2014-12-19 15:53:07

标签: php mysql json

我有以下json格式数据:

{"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"}
       }}]
     }
   }
}

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

3 个答案:

答案 0 :(得分:1)

例如,将json放在变量$str中,而不是访问项目:

$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>";
}

答案 1 :(得分:0)

使用json_decode将其转换为数组:

$array = json_decode($json_data, true);

然后,您可以访问项目,预测和高/低值:

$high = $array[1]['item']['forecast']['high'];

答案 2 :(得分:0)

假设你的json字符串是变量$ json:

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