I am new to Wordpress Plugin Developement,Wrote a function that requests a url for data and gets the same in Json Format,The Function Snippet is as follows;
function user_det()
{
$em = '';
$url = ''.$em;
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
echo '<pre>' , print_r($myhtml) , '</pre>';
}
The Output:
{
"Status":"Success",
"Bookings":[
{
"Message":"",
"Detail":{
"ServiceType":"",
"HoName":"",
"HAddress1":"",
"ToRooms":"",
"RoDetail":[
{
"RoomTypeDescription":[
" "
],
"NumberOfRooms":"",
"Passengers":[
{
"Salutations":"",
"FirstName":"",
"LastName":""
},
{
"Salutations":"",
"Age":"",
"CotBedOption":""
}
],
"totalAdult":2,
"totalChild":0
}
],
"Phone":"-",
"Rating":"",
"email":""
}
}]}
However ,Is there a way where I could Display the data in a tabular format,tried searching online but could not understand
As you are getting the information in JSON format from your API request, you'll need to iterate each element to format the way you want, example of building a table using this information.
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
$dataArray = json_decode($myhtml,1);
echo '<table>';
echo '<thead><tr><th>Service Type</th></tr></thead>';
echo '<tbody>';
// Now we have the json converted into an array, let's iterate it
foreach($dataArray["Bookings"] as $idx=>$bookingData) {
// Iterate all bookings and write on the rows
echo '<tr>';
echo '<td>'.$bookingData['Detail']['ServiceType'].'</td>';
echo '</tr>';
}
echo '</tbody><table>';
I believe this gives you the idea on what you need to perform to get your object and build a table.
Related
I am parsing data from JSON in Android, but JSON response is behaving strangely.
If it contains more than one data the response is like this
{"e":"701",
"data":[{"id":"121"},
{"id":"122"}
]
}
If it contains only one data the response is like this
{"e":"701",
"data":{"1":{"id":"93"}}
}
The code that send JSON response is
$r1=mysql_query($sql1,$con);
$count1=mysql_num_rows($r1);
if($count1>0)
{
while ($row1 = mysql_fetch_assoc($r1)) {
$data1[$i] = $row1 ;
}
}
$c = new Emp();
$c->e = "801";
$c->data =$data1;
echo json_encode($c);
How to parse this in one stretch? Any help would be appreciated.
How about you add this in the while loop ($e will be a variable which in the case above contains 801)
$info = array('e' => $e,
'data' => $data1
);
$rows[] = $info;
and then out of the while loop you take it out with json as an array which will give you the result you need if I get the question right.
echo str_replace("\\","", json_encode($rows));
I have some JSON I need to parse in a file test.json.
{
"players":
[
{ "SteamId":123, "Username":"Bob", "Kills":5, "Deaths":7, "Rank":1 },
{ "SteamId":456, "Username":"Nick", "Kills":3, "Deaths":2, "Rank":2 },
{ "SteamId":789, "Username":"Moses" "Kills":8, "Deaths":1, "Rank":3 }
]
}
How can I loop through and display my data. My code so far when I var_dump gives me a NULL
$raw_data = file_get_contents('test.json');
$data = json_decode($raw_data, true);
var_dump($data);
Your code is fine once you place the comma Saty mentioned.
To loop and print some values it would look something like:
foreach($data["players"] as $player){
print "Steam ID: ".$player['SteamId'];
print "Username: ".$player['Username'];
print "Kills: ".$player['Kills'];
print "Deaths: ".$player['Deaths'];
print "Rank: ".$player['Rank'];
}
This could be improved to automatically use the Key value as output with the following:
foreach($data["players"] as $player){
foreach($player as $key => $value){
print $key.": ".$value;
}
}
Depends what you are trying to accomplish and how the data will be viewed, but I expect you would be using HTML template.
I want the following json data created with php.
I'am getting the required values from my database.
JSON i want to output(I created it manually to show):
{
"room":[
{
"id":"1",
"temp":"20"
},
{
"id":"2",
"temp":"30"
}
]
}
Current PHP:
$rows = array();
if(!$allData->count()) {
echo 'No results!';
} else {
foreach ($allData->results() as $allData) {
$rows['id'] = $allData->id;
$rows['data'] = $allData->temp;
}
}
// echo out as json data
echo '{"rom":'.json_encode($rows).'}';
This is what my current PHP script outputs:
{"rom":{"id":"2","data":"20"}}
JSON formatted:
{
"rom":{
"id":"2",
"temp":"30"
}
}
As you can see it outputs only the last id and temp values..
I can't seem to find out what I'am doing wrong, any help is greatly appreciated.
You are missing one dimension in your array:
$rows = array();
if(!$allData->count()) {
echo 'No results!';
} else {
foreach ($allData->results() as $allData) {
$rows[] = [
'id' => $allData->id,
'data' => $allData->temp,
];
}
}
Consider this:
$rows[] = ["id"=>$allData->id, "data"=>$allData->temp];
I n this way you never overwrite previous data
I need to convert the below result. I generate this JSON array using PHP but now I need the same result into a single curly brace. Below is my PHP code to generate the JSON.
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[] = array(
'code' => array_search($obj['name'], $countries_iso),
'total' => $obj['Total']
);
}
}
header("Content-type: application/json");
#Output the JSON data
print (json_encode($arr));
Output of above PHP code:
[
{
code: "AF",
total: 1
},
{
code: "DZ",
total: 1
},
{
code: "AS",
total: 2
}
]
But I want to show like below result:
{
"AF":1
"DZ": 1,
"AS": 2
}
I guess you want $arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
Your mistake was the fact that you were declaring a new array each time you add something to your original array. This way you assign the correct way :)
Try this code:
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
}
}
header("Content-type: application/json");
#Output the JSON data
//$json = json_encode($arr);
$json = json_encode($arr);
Just do this:
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
But you can get rid of the whole array_search($obj['name'], $countries_iso) if you restrict the query to only return rows WHERE name IN (list of $countries_iso). Look up WHERE and IN for SQL Server.
You need to transform your data structure to an associative array, where the value you are currently storing in code will be the key and the value stored in total will be value.
I'll be able to help better if you post the code that generates your current JSON object
I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1