Array format inside JSON response using php - php

Send data from PHP platform to Android platform using "REST" API call .
I am facing issue in forming exact structure (how to structure" array inside json) .
I am new to REST API (REQUEST and RESPONSE)
please help me to solve this problem
The php code is as below:
case 'question':
$lesson = $_POST['lesson'];
$chapter = $_POST['chapter'];
if(!isset($lesson) || !isset($chapter)){
$response['error'] = true;
$response['message'] = 'key and values is empty (or) wrong';
http_response_code(404);
}
//for login we need the username and password
if(isTheseParametersAvailable(array('lesson','chapter'))){
//getting values
$lesson = $_POST['lesson'];
$chapter = $_POST['chapter'];
//creating the query
$query = "SELECT que_desc,option1,option2,option3,option4,true_ans FROM question WHERE lesson = '".$lesson."' AND chapter = '".$chapter."' ";
$result = mysqli_query($conn, $query);
// $user =array();
$questions =array();
$q = array();
$question = array();
$options = array();
$i=1;
//$j=0;
while($row = mysqli_fetch_assoc($result)){
$q["q".$i]['question'] = $row['que_desc'];
$q["q".$i]['option'][1] = $row['option1'];
$q["q".$i]['option'][2] = $row['option2'];
$q["q".$i]['option'][3] = $row['option3'];
$q["q".$i]['option'][4] = $row['option4'];
$q["q".$i]['answer'] = $row['true_ans'];
$i++;
}
$questions['questions'] = $q;
header('Content-Type: application/json');
echo json_encode($questions , JSON_FORCE_OBJECT);
exit;
}
break;
Below Code with "Structure Error"
{
"questions": {
"q1": {
"question": "question 1",
"option": {
"1": "option1",
"2": "option2",
"3": "option3",
"4": "option4"
},
"answer": "4"
},
"q2": {
"question": "question2",
"option": {
"1": "option1",
"2": "option2",
"3": "option3",
"4": "option4"
},
"answer": "2"
}
}
}
Expected Answer
{
"questions": {
"q1": {
"question": "question1",
"options": [
"option1",
"option2",
"option3",
"option4"
],
"answer": "option1"
},
"q2": {
"question": "question 2",
"options": [
"option1",
"option2",
"option3",
"option4"
],
"answer": "option2"
}
}
}
thanks in Advance .

Try using array :
while($row = mysqli_fetch_assoc($result)){
$q["q".$i]['question'] = $row['que_desc'];
$q["q".$i]['option'] = array($row['option1'], $row['option2'], $row['option3'], $row['option4']);
$q["q".$i]['answer'] = $row['true_ans'];
$i++;
}

Related

Compare variable of two different array?

Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.

Multidimensional array combines same key and value into already defined array element

I new to php, getting mysql results storing json but its not gettng coorect format what I want.
Pease check below code
$sql = "select * from en_providers where providerEmailAddress='" . $email . "' and providerPW='" . $password . "'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
$providerID = $row['providerID'];
$resultArray['providers'] = $row;
$resultArray['providers']['providerIDActivities'] = unserialize($row['providerIDActivities']);
$resultArray['providers']['providerIDBodies'] = unserialize($row['providerIDBodies']);
$resultArray['providers']['providerIDOthers'] = unserialize($row['providerIDOthers']);
$sql1 = "select * from en_venues where providerID = $providerID ";
$result1 = mysqli_query($con, $sql1) or die("Error in Selecting " . mysqli_error($connection));
$i = $j = $l = $x = $m = 0;
while ($row1[] = mysqli_fetch_assoc($result1)) {
//$resultArray['venues'][]['venueIDFacilities'] = unserialize($row1[$j++]['venueIDFacilities']);
$venueID = $row1[$j++]['venueID'];
$k = 0;
$venueFacilities = unserialize($row1[$i++]['venueIDFacilities']);
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
//$resultArray['venues'][$x++]['venueID'] = $venueID;
$resultArray['venues'] = $row1;
//echo json_encode($resultArray);
echo json_encode($resultArray);
}
}
Output is:
{
0: {
"venues": {
"venueIDFacilities": [
"1",
"2",
"3"
],
}
},
1: {
"venues": {
"venueIDFacilities": [
"4",
"7"
],
}
}
},
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2"
},
1: {
"venueID": "238",
"providerID": "2",
"venueActive": "yes"
}
}
But I need those VenueFailities to be in respective venues but result is getting outside. How can I append those values into venues?
I am trying for one day with different ways but it's not getting correct format.
Output I want:
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2",
"venueIDFacilities": [
"4",
"7"
]
},
1: {
"venueID": "238",
"providerID": "2",
venueIDFacilities": [
"4",
"7"
]
}
}
This line
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
should be
$resultArray['venues'][$x++]['venueIDFacilities'] = $venueFacilities;

Generate JSON Array from PHP SQL Loop

I need to generate the following JSON from a PHP loop and SQL DB but I'm having trouble:
[
{
"ItemName": "Websites1",
"Websites1": [
{
"0": "1",
"ID": "1",
"1": "Essential",
"WebsiteName": "Essential 1",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 1",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 1",
"2": "SO",
"WebsiteCode": "SO"
}
]
},
{
"ItemName": "Websites2",
"Websites2": [
{
"0": "1",
"ID": "1",
"1": "Essential Ibiza",
"WebsiteName": "Essential 2",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 2",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 2",
"2": "SO",
"WebsiteCode": "SO"
}
]
}
]
I have the relevant data being returned from the DB into PHP fine but I can't work out how to generate the relevant key value pairs and nesting using PHP loops. The code I have so far is:
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json = array();
while ($row = $this->db->row_read($rs)) {
$json["ID"] = $row["ID"];
$json["SelectText"] = $row["SelectText"];
$json["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2 = array();
while ($row = $this->db->row_read($rs)) {
$json2["ID"] = $row["ID"];
$json2["SelectText"] = $row["SelectText"];
$json2["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I'm obviously doing something very wrong as I only end up with one row for each query. The key value pairs are being overwritten with each loop. Also the nesting isn't correct. Sorry for such a dumb question but I've been trying to figure this out from info online and am stuck.
Thanks,
Noon.
EDIT - Managed to fix this using the annswer provided by Anushil Nandan below but the PHP needed a few extra tweaks to get the required format as folows:
// -----------------------------------------------------------------------------------------------
// BANNERMANGEMENTFORM
function bannerManagementJson($JsonItem) {
$this->db->connect();
$response = array();
//Generate Websites drop-down
$SqlStr = "SELECT WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Websites',1);
//Generate Clients drop-down
$SqlStr = "SELECT ClientName AS SelectText, ID AS SelectValue FROM Banners_BannerClients ORDER BY ClientName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Clients',2);
return json_encode($response);
}
// -----------------------------------------------------------------------------------------------
// RETRIEVEFORMELEMENTJSON
function retrieveFormElementJson($SqlStr,$ElementName,$SelectListNo) {
$this->db->sql = $SqlStr;
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json = array();
while ($row = $this->db->row_read($rs)) {
$json[] = $row;
}
$arrayResponse = array("ItemName"=>$ElementName, "SelectList" . $SelectListNo=>$json);
}
return $arrayResponse;
}
your array is being overridden every time it's entering while loop
try:
$json1[] = array();
$json2[] = array();
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json[] = array();
while ($row = $this->db->row_read($rs)) {
$json[]["ID"] = $row["ID"];
$json[]["SelectText"] = $row["SelectText"];
$json[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2[] = array();
while ($row = $this->db->row_read($rs)) {
$json2[]["ID"] = $row["ID"];
$json2[]["SelectText"] = $row["SelectText"];
$json2[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';

How do I format this data in to json using PHP so google chart could understand it?

$result = $db->query($select_msgsum); //query the new msgsum table
//defining label that google needs
$col1 = array();
$col1["id"]="";
$col1["label"]="MessageType";
$Col1["pattern"]="";
$col1["type"]="string";
$col2 = array();
$col2["id"]="";
$col2["label"]="MessageCount";
$Col2["pattern"]="";
$col2["type"]="number";
// rows?
//filling the json data to it
while($data=$result->fetchArray()){
array_push($col1, $data['msg_type']);
array_push($col2, $data['msg_count']);
}
$cols = array($col1, $col2);
file_put_contents('../json/chart_data.json', json_encode($cols));
?>
The result i get is as following which is not accepted as explained here: https://developers.google.com/chart/interactive/docs/php_example
[
{
"0": "General question",
"1": "Job-fulltime",
"2": "Job-parttime",
"3": "Just Hello",
"id": "",
"label": "MessageType",
"type": "string"
},
{
"0": 6,
"1": 3,
"2": 9,
"3": 12,
"id": "",
"label": "MessageCount",
"type": "number"
}
]
you can directly convert the result from query to JSON.. try this ..
$result = $db->query($select_msgsum);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);

Using PHP multidimensional arrays to convert MySQL to JSON

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.

Categories