create custom json array from database result in php? - 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);

Related

Encode table data to specific json format

Hi iam currently working on json based project.But iam having problem in encoding my data from my table like the below format.....I have seen a lot of json formats.....If any one can help me providing
php code snippet to encode exactly to such format.....
I need exactly such output where "data" is the array name
{
"data":[
{
"Id":1,
"Name":"Haben",
"Surname":"Dave",
"Age":22
},
{
"Id":12,
"Name":"Tomas",
"Surname":"Haleka",
"Age":32
},
{
"Id":123,
"Name":"Henok",
"Surname":"Dave",
"Age":28
},
{
"Id":1,
"Name":"Nafta",
"Surname":"Dave",
"Age":22
}
]
}
This will iterate through all selected rows and will encode them as Array. If you want to receive column names as they're in the table use below code.
$sql_query = "........";
$result = $db_connection->query($sql_query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode(array('data'=> $rows));
If you don't want to receive same column names as in database you can change how you want to receive them. You'll have to edit your while loop to do so.
while($r = mysqli_fetch_assoc($result)) {
$id = $r['user_id'];
$name = $r['user_name'];
$age = $r['user_age'];
$surname = $r['user_surname'];
$rows[] = array('Id' => $id, 'Name' => $name, 'Age' => $age, 'Surname' => $surname);
}

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']
));

Need help constructing json with 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

MySQL to JSON (For use with NVD3.js)

I'm trying to export the MySQL table below:
id, asof, value
abc, 2013-06-30, 36000000
abc, 2013-12-31, 48000000
abc, 2014-01-31, 51000000
abc, 2014-02-28, 56000000
xyz, 2013-06-30, 26000000
xyz, 2013-12-31, 33000000
xyz, 2014-01-31, 33000000
xyz, 2014-02-28, 36000000
into the following json format for use in the nvd3.js charts:
[
{
"key" : "abc" ,
"values" : [ [ 2013-06-30, 36000000] , [ 2013-12-31, 48000000] , [ 2014-01-31, 51000000] , [ 2014-02-28, 56000000]
},
{
"key" : "xyz" ,
"values" : [ [ 2013-06-30, 26000000] , [ 2013-12-31, 33000000] , [ 2014-01-31, 33000000] , [ 2014-02-28, 36000000]
}
]
I'm sure this is a newbie question but I'm struggling with it. Any guidance would be much appreciated!
Edit:
I've currently been trying to use an array and while statement but have not been able to figure out how to modify the array to so that it can output to the correct json format.
$query= mysqli_query($db,"SELECT id, asof, value
FROM table;"
);
if ( ! $query) {
echo mysqli_error();
die;
}
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);
Probably the most straightforward way of doing this is simply creating a multidimensional array, filling it with data obtained from database and then using json_encode to create a JSON string, which is then sent to the client.
Here is a simple example of a function which will accept an array of items and return a JSON string in the expected format. For simplicity, it is assumed that data was is a 2D array with three columns, but you should modify it to use the format returned by a database query.
function convert($data) {
$intermediate = array();
// This intermediate steps is used just to group all rows with
// the same key
foreach($data as $item) {
list($key, $date, $value) = $item;
$intermediate[$key][] = array($date, $value);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
'key' => $key,
'values' => $values
);
}
return $output;
}
Since you're getting data from database, variable $item inside the first foreach statement might actually be an associate array, so you'll have to write something like $item['key'] to get data for columns in the current row.
If you want to use mysqli_fetch_assoc, then you might try calling the function convert in the following way:
$conn = mysqli_connect('', '', '')
$query = 'SQL you wish to execute'
$result = mysqli_query($conn, $query)
if($result) {
$jsonData = convert($result);
}
However, function itself needs a little bit changing
function convert($result) {
$intermediate = array();
while($item = mysqli_fetch_assoc($result)) {
$key = $item['id'];
$date = $item['asof'];
$value = $item['value'];
$intermediate[$key][] = array($date, $value);
}
// The rest of the function stays the same
}

MySQL data to JSON via PHP

Basically idea is to grab data from MySQL table and transform it to JSON.
This is how database table looks:
And this how should output be:
[
{"group1":[
{"val":"somevalue"},
{"val":"somevalue"}
]
},
{"group2":[
{"val":"somevalue"},
{"val":"somevalue"}
]
},
{"group3":[
{"val":"somevalue"}
]
}
]
My PHP script looks like this, for now:
$arr = [];
$result = mysql_query("SELECT * FROM thetable WHERE section='sect1'");
while($row = mysql_fetch_array($result))
{
// ???
}
echo json_encode($arr);
My main issue is how to output/sort data in "groups".
Thanks for your help!
try this
while($row = mysql_fetch_array($result))
{
$arr[$row['group']][] = array('val' => $row['value']);
}

Categories