Parsing Complex JSON with PHP - php

I am new to PHP and not very clear how to parse JSON with PHP. This is the JSON i am getting from a third party
{ "data":
{ "current_condition":
[
{"cloudcover": "0", "humidity": "13", "observation_time": "05:47 AM", "precipMM": "0.0",
"pressure": "1016", "temp_C": "20", "temp_F": "69",
"visibility": "10", "weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
" winddir16Point": "SW", "winddirDegree": "218", "windspeedKmph": "12", "windspeedMiles": "7"
}
],
"request": [
{"query": "Lat 32.12 and Lon 76.53", "type": "LatLon" }
],
"weather": [
{
"date": "2012-11-04", "precipMM": "0.0", "tempMaxC": "20", "tempMaxF": "69", "tempMinC": "1", "tempMinF": "34",
"weatherCode": "113", "weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "SW", "winddirDegree": "218", "winddirection": "SW", "windspeedKmph": "12", "windspeedMiles": "8"
},
{
"date": "2012-11-05", "precipMM": "0.0", "tempMaxC": "20", "tempMaxF": "67", "tempMinC": "4", "tempMinF": "39",
"weatherCode": "113", "weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "SSW", "winddirDegree": "210", "winddirection": "SSW", "windspeedKmph": "12", "windspeedMiles": "7"
}
]
}
}
I am getting this weather information as JSON data which includes following information
Current information
Weather information for next 2 days
I do not want all information but only specific one like
current_condition
temp_C
temp_F
weatherDesc
Than i want some data from the weather information provides for next 2 days
date
tempMaxC
tempMinC
weatherIconUrl
windspeedKmph
i tried this code in PHP
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($weather, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
which seems to give me the JSON decoded data in the array format but i got confused in how to fetch those specific values from the PHP data. I can iterate over the Data
foreach ($jsonIterator as $key => $value) {
if(is_array($value)) {
foreach ($value as $key => $value) {
}
} else {
// echo "$key\n";
}
but not sure how to fetch values as described above.Any help or pointer for resources will really be helpful

Why don't you just use json_decode and then process the resulting object?
Example: http://codepad.org/ciw3ogAu
I used ob_get_content() because I don't want to mess up with the escape sequences, but the focus is on this line:
$result = json_decode($my_json_string);
It's not difficult to obtain information. For example if you want the current temperature in Celsius:
echo $result->data->current_condition[0]->temp_C;
You can get an array of the future two days (http://codepad.org/bhOcd3eT):
$weatherarray = $result->data->weather; // An array with two elements
You use $result->xxx instead of $result["xxx"] because json_decode will create objects for objects. You can change it to be arrays by calling json_decode($my_json_string, true), then you access members using the following way:
echo $result["data"]["current_condition"][0]["temp_C"];

You need to decode your json object, but you don't need to iterate it. Just access the information you want :
$decoded = json_decode($weather);
$date = $data->current_condition->data->weather->date;
$tempMaxC = $data->current_condition->data->weather->tempMaxC;
$tempMinC = $data->current_condition->data->weather->tempMinC;
$weatherUrl = $data->current_condition->data->weather->weatherIconUrl;
$windspeedKmph = $data->current_condition->data->weather->windspeedKmph;

I would go with this approach to access your data :
$data = json_decode($weather);
And then your can easily get what you want this way :
print_r($data->data->current_condition);
or in a loop...

$decode=json_decode($file);
echo $decode->data->current_condition[0]->temp_C;
echo $decode->data->current_condition[0]->temp_F;
echo $decode->data->current_condition[0]->weatherDesc[0]->value;
foreach ($decode->data->weather as $data) {
echo $data->date;
echo $data->tempMaxC;
echo $data->tempMinC;
echo $data->weatherIconUrl;
echo $data->windspeedKmph;
}

Related

PHP access foreach to iterate json data multiple object

I'm facing an error when trying to post JSON data into PHP. I am new at this.
any helps makes good for us
the JSON looks like this:
[
{
"sections": [
{
"section_id": "62",
"section_name": "English Language",
}
]
},
{
"questions": [
{
"section_id": "62",
"questionid": "1231",
},
{
"section_id": "62",
"questionid": "1232",
"time_spent": "0",
"status": "unseen",
"testsession_id": "whqgo41nsyurpi2"
},
{
"section_id": "62",
"questionid": "1233",
}
]
}
]
below is the code I wrote. Please correct the PHP code to access those JSON values.
$data = json_decode(file_get_contents("php://input"),true);
foreach ($data['sections'] as $value){
echo $value[section_id];
}
foreach ($data['questions'] as $value){
echo $value[section_id];
}
You are missing the array aspect of the JSON. The JSON is made up of an array firstly, which contains 2 objects, which have parameters of sections in the first, and questions in the second.
sections and questions are both arrays, which can be iterated over using foreach, which returns each of the elements as an object.
Your code after decoding the JSON should be like this.
foreach ($data[0]['sections'] as $value){
echo $value['section_id'];
}
foreach ($data[1]['questions'] as $value){
echo $value['section_id'];
}

Laravel Query to select list entry in JSON field

I'm storing dynamic data in a MySQL JSON field using Laravel v6.11.0, nova v2.9.3 and nova-flexible-content v0.1.13. The data stored looks similar to this:
[
{
"layout": "source",
"key": "5ce8e0a877487fe5",
"attributes": {
"value": "342",
"unit": "USD",
"language": "en",
"url": "http:\\/\\/google.com",
"authority": "google.com",
"entry_date": "2020-01-21",
"date": "2019-12-21"
}
},
{
"layout": "source",
"key": "a82393ce016e8c14",
"attributes": {
"value": "444",
"unit": "USD",
"language": "en",
"entry_date": "2020-01-21",
"url": "https:\\/\\/google.com",
"authority": "TEST",
"date": "2020-01-20"
}
}
]
I was wondering if it's possible to build a Laravel Query to select the second entry based on the authority entry? Criteria are:
url should contain google.com AND
authority shouldn't be google.com
I've found https://laravel.com/docs/5.8/queries#json-where-clauses, but am struggling to put the right query together. Maybe someone could give me some pointers on how to do it? Thank you
You may refer to this discussion on Laracast
$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
->get();
foreach ($data as $key => $row) {
$bodyArr = json_decode($row->body);
foreach ($bodyArr as $item) {
if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false)) {
dump($item);
// YOUR CODE GOES HERE
}
}
}

PHP: Create JSON from MySql to look like this. Consume in Swift 3

My query is:
"SELECT day, title, speaker, time, room, details FROM classes"
I would love to know how to create JSON to look exactly like this from a MySql table in PHP:
{
"DAY" : "MONDAY": [
{
"TITLE": "TEST DRIVEN DEVELOPMENT",
"SPEAKER": "JASON SHAPIRO",
"TIME": "9:00 AM",
"ROOM": "MATISSE",
"DETAILS": "EXPLORE THE TOPICS AND TOOLS RELATED TO TEST DRIVEN DEVELOPMENT."
},
{
"TITLE": "JAVA TOOLS",
"SPEAKER": "JIM WHITE",
"TIME": "9:00 AM",
"ROOM": "ROTHKO",
"DETAILS": "DISCUSS THE LATEST SET OF TOOLS USED TO HELP EASE SOFTWARE DEVELOPMENT."
}
],
"DAY" : "TUESDAY": [
{
"TITLE": "MONGODB",
"SPEAKER": "DAVINMICKELSON",
"TIME": "1: 00PM",
"ROOM": "PICASSO",
"DETAILS": "LEARNABOUT\"NOSQL\"DATABASES."
},
{
"TITLE": "DEBUGGINGWITHXCODE",
"SPEAKER": "JASONSHAPIRO",
"TIME": "1: 00PM",
"ROOM": "VANGOGH",
"DETAILS": "EXPLOREDIFFERENTPATTERNSFORDEBUGGINGYOURIOSAPPS."
}
],
[
Day etc....
]
}
I am assuming I can't get this to work because of the word "DAY:" prior to the actual day. But how would I consume this in Swift 3 being each day is dynamically generated? My ultimate goal is to create properly formatted JSON and consume it efficiently in Swift 3 tableview (for the days - vertically scrolled) and collection view (for the titles - horizontally scrolled in each table row).
Using same key in JSON will cause unintended result.
Below is valid JSON Formation.
{
"MONDAY": [
{
"TITLE": "TEST DRIVEN DEVELOPMENT",
"SPEAKER": "JASON SHAPIRO",
"TIME": "9:00 AM",
"ROOM": "MATISSE",
"DETAILS": "EXPLORE THE TOPICS AND TOOLS RELATED TO TEST DRIVEN DEVELOPMENT."
},
{
"TITLE": "JAVA TOOLS",
"SPEAKER": "JIM WHITE",
"TIME": "9:00 AM",
"ROOM": "ROTHKO",
"DETAILS": "DISCUSS THE LATEST SET OF TOOLS USED TO HELP EASE SOFTWARE DEVELOPMENT."
}
],
"TUESDAY": [
{
"TITLE": "MONGODB",
"SPEAKER": "DAVINMICKELSON",
"TIME": "1: 00PM",
"ROOM": "PICASSO",
"DETAILS": "LEARNABOUT\"NOSQL\"DATABASES."
},
{
"TITLE": "DEBUGGINGWITHXCODE",
"SPEAKER": "JASONSHAPIRO",
"TIME": "1: 00PM",
"ROOM": "VANGOGH",
"DETAILS": "EXPLOREDIFFERENTPATTERNSFORDEBUGGINGYOURIOSAPPS."
}
],
[
Day etc....
]
}
create a sort function
// create a sort function
// put the whole result array to res
function sortResultByDay($res) {
$returnArray = array();
foreach($res as $row) {
$day = $row['day'];
unset($row['day']);
$returnArray[$day][] = $row;
}
return $returnArray;
}
and use the function like this
$res = mysql_query("SELECT day, title, speaker, time, room, details FROM classes");
$resArray = array();
while($row = mysql_fetch_assoc($res))
$resArray[] = $row;
$resArraySorted = sortResultByDay($resArray);
echo json_encode($resArraySorted);

Decode json in php and create variables

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.
You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

PHP JSON data foreach problem

I want to make a PHP JSON data foreach, but I met some problem. First: I can not get the properties part. Second it alawys show wrong in line: echo '<div class="image">...
Fatal error: Cannot use object of type stdClass as array in ...
This is the json data:
[
{
"post_id": "504464716_189878284371815",
"message": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"attachment": {
"media": [
{
"href": "http:\/\/www.facebook.com\/photo.php?fbid=493710409716&set=a.453260184716.254996.504464716",
"alt": "",
"type": "photo",
"src": "http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs049.snc4\/34793_493710409716_504464716_5821684_2056840_s.jpg",
"photo": {
"aid": "2166659457206182932",
"pid": "2166659457211749620",
"owner": 504464716,
"index": 24,
"width": 225,
"height": 225
}
}
],
"name": "Wall Photos",
"href": "http:\/\/www.facebook.com\/album.php?aid=254996&id=504464716",
"caption": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"description": "",
"properties": [
{
"name": "By",
"text": "Suman Acharya",
"href": "http:\/\/www.facebook.com\/profile.php?id=504464716"
}
],
"icon": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/yD\/r\/aS8ecmYRys0.gif",
"fb_object_type": "album",
"fb_object_id": "2166659457206182932"
},
"action_links": null,
"privacy": {
"value": ""
}
},
...
]
Here is my php code:
foreach ($data as $result) {
echo '<div class="title">'.htmlspecialchars($result->message).'<br />'.htmlspecialchars($result->description).'<br />'.htmlspecialchars($result->caption).'<br />';
if(!empty($result->attachment->properties[0]->text)){
foreach ($result->attachment->properties[0] as $properties) {
echo htmlspecialchars($properties->name).'<br />'.htmlspecialchars($properties->text).'</div>';
}
}
if(!empty($result->attachment->media)){
echo '<div class="image"><img src="'.htmlspecialchars($result->attachment->media[0]->src).'" /><br>'.htmlspecialchars($result->attachment->media[0]->type).'</div>';
}
}
If i were you i would just force the decoding to an assoc array by true as the second arg to json_decode. If you cant or dont want to do that then try accessing it like this:
$result->attachment->media->{0}->href
Use json_decode($the_data, true); instead of json_decode($the_data); that way it will return you an associative array instead of a StdClass.

Categories