I'm trying to create a questionnaire app in Android and I can already get the questions from the database and show it as JSON Array but it will be displayed in this format:
{
"result": [
{
"id_question": "1",
"question_name": "Grade level",
"choices": "Grade 11, Grade 12"
},
{
"id_question": "2",
"question_name": "Expected grade in this subject",
"choices": "90-100, 75-89, 60-74, Below 60"
}
]
}
But the library I'm using in Android is only accepting this kind of JSON format for showing the questions:
{
"survey_properties": {
"intro_message": "To get a reliable result for the evaluation, please respond to all questions.",
"end_message": "Your answers have been recorded. <br>Thank you for taking the time to answer the evaluation."
},
"questions": [
{
"id_question": "1",
"question_name": "Grade Level",
"choices": [
"Grade 11",
"Grade 12"
]
},
{
"id_question": "2",
"question_name": "Expected Grade in this subject",
"choices": [
"90-100",
"75-89",
"60-74",
"Below 60"
]
}
]
}
How can I achieve this kind of output in PHP? This is the script I'm using:
$query = "SELECT * FROM question_test";
$r = mysqli_query($conn, $query);
$result = array();
while($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id_question"=>$row['id_question'],
"question_name"=>$row['question_name'],
"choices"=>$row['choices']
)
);
}
echo json_encode(array("result"=>$result));
From your code, it could be modified like this:
$query = "SELECT * FROM question_test";
$r = mysqli_query($conn, $query);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id_question"=>$row['id_question'],
"question_name"=>$row['question_name'],
"choices"=>explode(', ', $row['choices'])
));
}
echo json_encode(array("result"=>$result));
You have to add more information like survey_properties
What I'm trying to do here is put the "choices" into an array. Hope that works.
$query = "SELECT * FROM question_test";
$r = mysqli_query($conn, $query);
$result = array();
$choices = array();
while($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id_question"=>$row['id_question'],
"question_name"=>$row['question_name'],
array_push($choices,array($row['choices'])
)
);
}
echo json_encode(array("result"=>$result));
Related
Need to perform couple of mysqli queries and add one result into existing result array, currently I have implemented first query,
$dataQuery = "SELECT * FROM movies_table";
$sth = mysqli_query($conn, $dataQuery);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
$respObj->status = 'success';
$respObj->movies = $rows;
$respJSON = json_encode($respObj);
print $respJSON;
The result is like,
{
"status": "success",
"movies": [
{
"id": "8",
"image": "image-url-here",
"language": "english",
"title": "avengers",
"year": "2005",
"dir_id": "152"
}
]
}
Now I want to perform another query,
"SELECT * FROM directors_table WHERE director_id = $dir_id"
and add the result into json response as director object,
{
"status": "success",
"movies": [
{
"id": "8",
"image": "image-url-here",
"language": "english",
"title": "avengers",
"year": "2005",
"director": {
"id": "152",
"name": "director",
"age": 50
}
}
]
}
Use a JOIN in your query:
SELECT *
FROM movies_table m
INNER JOIN directors_table d ON d.director_id = m.dir_id
And build the array structure in your loop:
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = [
'id' => $r['id'],
'image' => $r['image'],
/* other movie keys you need */
'director' => [
'id' => $r['director_id'],
/* other director keys you need */
]
];
}
Two solutions
Make a JOIN like #AymDev suggested in the first comment to your question. This might be the preferred solution if your tables are relatively small and you don't have any performance issues
Double query
// First retrieve all the directors and keep an array with their info. The Key of the array is the director ID
$dataQuery = "SELECT * FROM directors_table";
$sth = mysqli_query($conn, $dataQuery);
$directors = array();
while($r = mysqli_fetch_assoc($sth)) {
$directors[$r['id']] = $r;
}
$dataQuery = "SELECT * FROM movies_table";
$sth = mysqli_query($conn, $dataQuery);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
// Retrieve the director info from the previous array
$r['director'] = $directors[$r['dir_id']];
$rows[] = $r;
}
$respObj->status = 'success';
$respObj->movies = $rows;
$respJSON = json_encode($respObj);
print $respJSON;
I'm new to php and am trying to encode 2 arrays together into one JSON object.
Currently this is the JSON output:
{
"image_link": "some url",
"zoomin_level": "8",
"zoomout_level": "18.5",
"position_lat": "32.913105",
"position_long": "-117.140363",
}
What I like to achieve is the following:
{
"image_link": "some url",
"zoomin_level": "2",
"zoomout_level": "15",
"position_lat": "32.9212",
"position_long": "-117.124",
"locations": {
"1": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
},
"2": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
}
}
}
This is similar to the question asked here: PHP json_encode multiple arrays into one object
However mine is a bit different because I like to add the 2nd array as part of a key-value part within the 1st array.
Here's my php code:
$sql = "select * from first_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rowCount = $result->num_rows;
$index = 1 ;
$newArray = [];
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from second_table";
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$locations[$indexnew] = array("image_link" => $rownew['image_link'], "name" => $rownew['name'], "position_lat" => doubleval($rownew['position_lat']), "position_long" => doubleval($rownew['position_long']) );
++$indexnew;
}
}
$newArray[$row['map_type']] = $row['map_value'];
}
echo json_encode($newArray);
Not knowing the proper syntax, I tried to perform the following which resulted in garbage: echo json_encode($newArray, "locations" =>$locations);
Try:
$newArray['locations'] = $locations;
echo json_encode ($newArray);
How do i encode two arrays that retrieves data from 2 different table in my database and encode it in 1 json response
Here is my php
$sql = "select * from schedule;";
$sql1 = "select * from matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$result1 = mysqli_query($con,$sql1);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("n_name"=>$row[1],"start"=>$row[4],"end"=>$row[5],"venue"=>$row[6]));
}
$data= array();
while($row=mysqli_fetch_array($result1))
{
array_push($data, array("teamone"=>$row[1], "teamtwo"=>$row[2], "s_name"=>$row[10]));
}
echo json_encode (array("server_response"=>$response, $data));
mysqli_close($con);
?>
What i want is something like this
{
"server_response": [{
"n_name": null,
"start": "2016-11-09 00:00:00",
"end": "2016-11-16 00:00:00",
"venue": "aaaaaa",
"teamone": "aaa",
"teamtwo": "bbb",
"s_name": ""
}]
}
Instead i get something like this
{
"server_response": [{
"n_name": null,
"start": "2016-11-09 00:00:00",
"end": "2016-11-16 00:00:00",
"venue": "aaaaaa"
}],
"0": [{
"teamone": "aaa",
"teamtwo": "bbb",
"s_name": ""
}]
}
Can someone help me. Thanks!
$response = array();
while($row=mysqli_fetch_array($result))
{
$response['server_response']["n_name"] = $row[1];
$response['server_response']["start"] = $row[4];
$response['server_response']["end"] = $row[5];
$response['server_response']["venue"] = $row[6];
}
while($row=mysqli_fetch_array($result1))
{
$response['server_response']["teamone"] = $row[1];
$response['server_response']["teamtwo"] = $row[2];
$response['server_response']["s_name"] = $row[10];
}
echo json_encode ($response);
echo json_encode (array("server_response"=>array_merge($response, $data)));
or
echo json_encode (array("server_response"=>$response + $data)); // if you run the risk of same key existing in both arrays
I have developed an api which will post some data in json format to be used in an android app. However I am getting json parsing error. I am new to this whole json thing so unable to understand what the error means.
This is my json encoded output that the php backend generates
{
"data": [
{
"id": "2",
"name": "Rice",
"price": "120",
"description": "Plain Rice",
"image": "6990_abstract-photo-2.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
}
]
}{
"data": [
{
"id": "4",
"name": "Dal",
"price": "5",
"description": "dadadad",
"image": "",
"time": "20 mins",
"catagory": "Dinner",
"subcat": ""
}
]
}{
"data": [
"catagory": "Soup"
]
}
This is the error the online json parser gives
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What is actually wrong here? Could you please provide me with the correct json output for the following data?
This should clear it up
$main = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'"; //Prepare login query
$value = $DBH->query($query1);
if($row1 = $value->fetch(PDO::FETCH_OBJ))
{
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
You shouldn't create your json string by hand. Create your array structure, then finally invoke json_encode() at the end.
$data = array();
try
{
$query = "SELECT category FROM category"; // select category FROM category? what?
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($value->rowCount() > 0) {
$data[] = array('data' => $value->fetch(PDO::FETCH_ASSOC));
}
else {
$sub = array('category' => $row['category']);
$data[] = array('data' => $sub);
}
}
$result->closeCursor();
$DBH = null;
echo json_encode($data); // encode at the end
}
catch(PDOException $e)
{
print $e->getMessage ();
die();
}
Here's my table structure.
I'm trying to convert MySQL to nested JSON, but am having trouble figuring out how to build the multidimensional array in PHP.
The result I want is similar to this:
[
{
"school_name": "School's Name",
"terms": [
{
"term_name":"FALL 2013",
"departments": [
{
"department_name":"MANAGEMENT INFO SYSTEMS",
"department_code":"MIS",
"courses": [
{
"course_code":"3343",
"course_name":"ADVANCED SPREADSHEET APPLICATIONS",
"sections": [
{
"section_code":"18038",
"unique_id": "mx00fdskljdsfkl"
},
{
"section_code":"18037",
"unique_id": "mxsajkldfk57"
}
]
},
{
"course_code":"4370",
"course_name":"ADVANCED TOPICS IN INFORMATION SYSTEMS",
"sections": [
{
"section_code":"18052",
"unique_id": "mx0ljjklab57"
}
]
}
]
}
]
}
]
}
]
The PHP I'm using:
$query = "SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN adoptions ON departments.id=adoptions.department_id";
$fetch = mysqli_query($con, $query) or die(mysqli_error($con));
$row_array = array();
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$row_array[$row['school_name']]['terms']['departments'][] = array(
'department_name' => $row['department_name'],
'department_code' => $row['department_code'],
'course_name' => $row['course_name'],
'course_code' => $row['course_code'],
'section_code' => $row['section_code'],
'unique_id' => $row['magento_course_id']
);
}
$return_arr = array();
foreach ($row_array as $key => $record) {
$return_arr[] = $record;
}
file_put_contents("data/iMadeJSON.json" , json_encode($return_arr, JSON_PRETTY_PRINT));
My JSON looks like this:
[
{
"school_name": "School's Name",
"terms": {
"term_name": "FALL 2013",
"departments": [
{
"department_name": "ACCOUNTING",
"department_code": "ACCT",
"course_name": "COST ACCOUNTING",
"course_code": "3315",
"section_code": "10258",
"unique_id": "10311"
},
{
"department_name": "ACCOUNTING",
"department_code": "ACCT",
"course_name": "ACCOUNTING INFORMATION SYSTEMS",
"course_code": "3320",
"section_code": "10277",
"unique_id": "10314"
},
...
The department information is repeated for each course, making the file much larger. I'm looking for a better understanding of how PHP multidimensional arrays in conjunction with JSON works, because I apparently have no idea.
I started from Ian Mustafa reply and I figure out to solve the problem of each loop erasing the previous array.
It's an old thread but I think this could be useful to others so here is my solution, but based on my own data structure (easy to figure out how to adapt it to other structures I think) :
$usersList_array =array();
$user_array = array();
$note_array = array();
$fetch_users = mysqli_query($mysqli, "SELECT ID, Surname, Name FROM tb_Users WHERE Name LIKE 'G%' ORDER BY ID") or die(mysqli_error($mysqli));
while ($row_users = mysqli_fetch_assoc($fetch_users)) {
$user_array['id'] = $row_users['ID'];
$user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
$user_array['notes'] = array();
$fetch_notes = mysqli_query($mysqli, "SELECT id, dateIns, type, content FROM tb_Notes WHERE fk_RefTable = 'tb_Users' AND fk_RefID = ".$row_users['ID']."") or die(mysqli_error($mysqli));
while ($row_notes = mysqli_fetch_assoc($fetch_notes)) {
$note_array['id']=$row_notes['id'];
$note_array['dateIns']=$row_notes['dateIns'];
$note_array['type']=$row_notes['type'];
$note_array['content']=$row_notes['content'];
array_push($user_array['notes'],$note_array);
}
array_push($usersList_array,$user_array);
}
$jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);
echo $jsonData;
Resulting JSON :
[
{
"id": "1",
"surnameName": "Xyz Giorgio",
"notes": [
{
"id": "1",
"dateIns": "2016-05-01 03:10:45",
"type": "warning",
"content": "warning test"
},
{
"id": "2",
"dateIns": "2016-05-18 20:51:32",
"type": "error",
"content": "error test"
},
{
"id": "3",
"dateIns": "2016-05-18 20:53:00",
"type": "info",
"content": "info test"
}
]
},
{
"id": "2",
"cognomeNome": "Xyz Georg",
"notes": [
{
"id": "4",
"dateIns": "2016-05-20 14:38:20",
"type": "warning",
"content": "georg warning"
},
{
"id": "5",
"dateIns": "2016-05-20 14:38:20",
"type": "info",
"content": "georg info"
}
]
}
]
Change your while to this:
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$row_array[$row['school_name']]['terms']['department_name'][] = array(
'department_name' => $row['department_name'],
'department_code' => $row['department_code']
);
}
Edit
If you want to achieve result like the example, maybe you should consider using this method:
<?php
$result_array = array();
$fetch_school = mysqli_query($con, "SELECT id, school_name FROM schools") or die(mysqli_error($con));
while ($row_school = mysqli_fetch_assoc($fetch_school)) {
$result_array['school_name'] = $row_school['school_name'];
$fetch_term = mysqli_query($con, "SELECT term_name FROM term_names WHERE school_id = $row_school['id']") or die(mysqli_error($con));
while ($row_term = mysqli_fetch_assoc($fetch_term)) {
$result_array['terms']['term_name'] = $row_term['term_name'];
$fetch_dept = mysqli_query($con, "SELECT id, department_name, department_code FROM departments WHERE school_id = $row_school['id']") or die(mysqli_error($con));
while ($row_dept = mysqli_fetch_assoc($fetch_dept)) {
$result_array['terms']['deptartments']['department_name'] = $row_dept['department_name'];
$result_array['terms']['deptartments']['department_code'] = $row_dept['department_code'];
$fetch_course = mysqli_query($con, "SELECT course_name, course_code FROM adoptions WHERE departement_id = $row_dept['id']") or die(mysqli_error($con));
while ($row_course = mysqli_fetch_assoc($fetch_course)) {
$result_array['terms']['deptartments']['courses']['course_name'] = $row_course['course_name'];
$result_array['terms']['deptartments']['courses']['course_code'] = $row_course['course_code'];
}
}
}
}
file_put_contents("data/iMadeJSON.json" , json_encode($result_array, JSON_PRETTY_PRINT));
Probably it's not an effective program, but it should gives you best result. Hope it helps :)
Try replacing your while loop with below code:
$departments = array();
$courses = array();
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$row_array[$row['school_name']]['terms']['term_name'] = $row['term_name'];
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms']['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms']['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms']['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
Hope this would help you.
I know that this is a kind of an old question, but today I was with the same issue. I didn't find a proper solution online and finally I solved, so I'm posting here so others can check.
I'm not 100% sure that this will work because I don't have your DB, but in my case was similar and worked. Also it will not be 100% like it was asked, but I'm pretty sure there will be no redundancy and all the data will be shown.
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['department_name'] = $row['department_name'];
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['courses']['course_code'][$row['course_code']]['course_name'] = $row['course_name'];
$row_array ['school_name'][$row['school_name']]['terms'][$row['term_name']]['departments']['department_code'][$row['department_code']]['courses']['course_code'][$row['course_code']]['sections']['unique_id'][$row['magento_course_id']]['section_code'] = $row['section_code'];
}
Also I'm not a PHP guy, but from what I understand, the = comes before a leaf and only before a leaf.