Reputation: 33
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?
Upvotes: 0
Views: 95
Reputation: 4334
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'];
Upvotes: 0
Reputation: 626
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>";
}
Upvotes: 1
Reputation: 758
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"]);
}
Upvotes: 0