Need help constructing json with PHP - php

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

Related

Display Php (json) output in tabular format

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.

JSON format getting only one column

I am new to PHP so far I managed to get the following output from database in JSON format.I created an array result which returns workorderName, but I want to get workOrderId also in the same array so that I can use it in android string request.
{
"result": [
{
"$workOrderName": "electrician"
},
{
"$workOrderName": "plumber"
},
{
"$workOrderName": "carpenter"
}
]
}
my php code is
<?PHP
require_once('connection.php');
$workName = "SELECT work_order_id,workorder_name FROM workorder_category";
$con=mysqli_connect($server_name,$user_name,$password,$db);
$r = mysqli_query($con,$workName);
$result = array();
$resultArr = array('success' => true);
while($row = mysqli_fetch_array($r)){
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I want the Output like
{
"result": [
{
"$workOrderId":"1"
"$workOrderName": "electrician"
},
{
"$workOrderId":"2"
"$workOrderName": "plumber"
},
{
"$workOrderId":"3"
"$workOrderName": "carpenter"
}
]
}
I'm pretty sure you didn't mean to have the $ in the key, but this is easier and will give you the column names (work_order_id, workorder_name) from the table as keys. Make sure to use mysqli_fetch_assoc:
while($row = mysqli_fetch_assoc($r)){
$result[] = $row;
}
If you want to change the keys then you can alias them in the query and use the above:
$workName = "SELECT work_order_id AS workOrderID, workorder_name AS workOrderName FROM workorder_category";
Or you could build the array:
$result[] = array('workOrderID' => $row['work_order_id'],
'workOrderName' => $row['workorder_name']);
You need to tweak your code to add $workOrderId also in the array like below
array_push($result,array(
'$workOrderId' => $row['work_order_id']
'$workOrderName' => $row['workorder_name']
));

PHP Json Help need?

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

JSON manipulation in PHP?

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

create custom json array from database result in php?

Hi I have some table say fro example table1 ,table2 in my mysql databse.
I need to get following json result from php.
Can anyone suggest how to achieve this?
any good tutorial doing same is also helpful.
I am able to convert database result in simple json response but custom response is something difficult for me.
{
response:ok
tables:[
{
name:table name
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
{
name:table name1
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
]
}
}
Quoting from How to convert mysql data base table data in json using php, once you have your table names you can do for each of them.
$result = array();
$result['response'] = 'ok'
foreach ($tables as $tableName) {
$query = mysql_query("SELECT * FROM $tableName");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
$result['tables'][] = array(
'name' = $tableName,
'data' = $rows
)
}
print json_encode($result);

Categories