I have 3 tables, after joining name and output the role with this
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
echo json_encode($res);
}
I got this
{"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"}
{"student_id":"1","student_name":"john","score_id":"2","score_type":"B","score_name":"Brazil"}
Now I'm struggling to turn them into the format I wanted, the client site have to have this
//json
[{
"student_id":"1",
"student_name":"john",
"scores": [{
"score_id":"1",
"score_type":"E",
"score_name":"England"
},{
"score_id":"2",
"score_type":"B",
"score_name":"Brazil"
}]
}]
The challenge is it has duplicated row with the same person.
Process the output using the Array $encoded and once it is built then you can print it with JSON.
In this solution the array will be indexed by student_id and the scores by score_id. In case of student it is a must, in case of scores it is recommended:
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
// Student's details
$encoded[$res['student_id']] = array(
'student_id' => $res['student_id'],
'student_name' => $res['student_name'],
);
// Student's score details
$encoded[$res['student_id']]['scores'][$res['score_id']] = array(
'score_id' => $res['score_id'],
'score_type' => $res['score_type'],
'score_name' => $res['score_name'],
);
}
echo json_encode($encoded);
Note: this is general answer since I do not know exact structure of your data in $res.
Please find the below code to get the json format as mentioned in your question
$students = [];
$sampleData = [
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"1",
"score_type"=>"E",
"score_name"=>"England",
],
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"2",
"score_type"=>"B",
"score_name"=>"Brazil",
],
];
foreach ($sampleData as $res) {
//if student not found by id then continue
if (empty($res['student_id'])) {
continue;
}
$student = [];
//get the already exists student to add scores
if(!empty($students[$res['student_id']])) {
$student = $students[$res['student_id']];
}
//prepare the student array
$student['student_id'] = $res['student_id'];
$student['student_name'] = $res['student_name'];
$student['scores'][]['score_id'] = $res['score_id'];
$student['scores'][]['score_type'] = $res['score_type'];
$student['scores'][]['score_name'] = $res['score_name'];
$students[$res['student_id']] = $student;
}
echo json_encode(array_values($students));
hope this helps
You can find the working example here
Related
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);
}
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']
));
I have a database with project entries. Each entry has a project title, datestamp, the user who entered it, and a comment. I am trying to format this data as JSON for reporting and charts.
I want an array for each project name, and inside that array an array for each entry.
I've tried several approaches but I haven't had much luck yet.
if ($result = $mysqli->query("SELECT * FROM project_entries"))
// WHERE WEEK(date) = WEEK(current_date) ORDER BY project_name
{
while ($row = mysqli_fetch_array($result)) {
$entry_array = array();
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array (
'comment' => $comment,
);
$row_array['entries'] = $entry;
if ( !in_array($row['project_name'], $projects, false ))
{
array_push($projects, $row_array);
}
}
}
Outputs:
[
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing"
}
},
{
"project_name": "Logo Design",
"entries": {
"comment": "Created some stuff"
}
},
While I want:
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing",
"comment": "Created some stuff"
}
}
This should do the trick. You can use the project name as an array key. In order to prevent the string keys from showing up in your output array, you can use array_values to convert them to numeric keys.
$projects = array();
while ($row = mysqli_fetch_array($result)) {
$projects[$row['project_name']]['project_name'] = $row['project_name'];
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
}
echo json_encode(array_values($projects));
What was going wrong with your previous code:
if ($result = $mysqli->query("SELECT * FROM project_entries")) {
while ($row = mysqli_fetch_array($result)) {
$entry_array = array(); // This does not appear to be used
// With each iteration of the while loop, you create a new array of
// project information (project name and entries array with one comment)
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array ('comment' => $comment);
$row_array['entries'] = $entry;
// The $projects array is an array of arrays, but $row['project_name'] is
// a string. Checking if this string is in an array of arrays will always
// be false, so the array_push should always execute.
if (!in_array($row['project_name'], $projects, false )) {
// Adds the new project array to the projects array
array_push($projects, $row_array);
}
// This is not producing what you want because you are adding a new
// array to $row_array each time the loop runs
}
}
Why the code I suggested works:
$projects = array(); // Empty array to hold all the projects
while ($row = mysqli_fetch_array($result)) {
// Using the project name from the database as an array key in the array we are
// constructing keeps the projects unique in that array.
// The first time a new project name occurs, this will create a new sub-array
// within $projects with project_name => the new project name. This value will
// be overwritten on subsequent occurrences of the same project name.
$projects[$row['project_name']]['project_name'] = $row['project_name'];
// For each iteration, this will add a comment to the 'entries' array in the
// project array with the key $row['project_name'].
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
// For example, with the first iteration of the array we create the following:
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'] ] ]
//
// with the second iteration, the project name is overwritten (with same project name)
// and another comment array is added to the entries array
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'],
// 1 => ['comment' => 'Created some stuff'] ] ]
}
// If you just did echo json_encode($projects), you would not get the format you want,
// because of the string keys. Try it without the array_values() to see what I mean.
echo json_encode(array_values($projects));
Maybe something like that?
Use project id to build target array.
while ($row = mysqli_fetch_array($result) {
if (!isset($projects[$row['id']]))
{
$projects[$row['id']] = [
'project_name' => $row['project_name'],
'entries' => [],
];
}
$projects[$row['id']]['entries'][] = [
'comment' => $row['comment'],
];
}
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
}
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);