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.
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;
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.
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) . ']';
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);
Hello I have this php code for printing json
<?php
include('databaseconnect.php');
$sql = "SELECT product_id,product_name FROM products WHERE product_id='1'";
$result = $conn->query($sql);
$sql2 = "SELECT GROUP_CONCAT(ss.Name,':',sv.value_s ) as Specifications FROM specifications ss, specification_value sv WHERE sv.specification_ID = ss.specification_ID AND sv.product_id = '1'";
$fetch = $conn->query($sql2);
$sql3 = "select GROUP_CONCAT(v.name,':',vv.value) as variants from variant v,variant_value vv where v.variant_id=vv.variant_id and product_id='1'";
$fetch1 = $conn->query($sql3);
$json['products'] = array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$json['products'] = $row;
}
$json['products']['specification'] = array();
while ($row = mysqli_fetch_assoc($fetch)){
$specification_array = explode(',', $row["Specifications"]);
$speci_array = array();
foreach($specification_array as $spec){
$spec = explode(':',$spec);
$speci_array[$spec[0]] = $spec[1];
}
$json['products']['specification'] = $speci_array;
//array_push($json['products'],$row_temp);
}
$json['products']['specification']['variants'] = array();
while ($row = mysqli_fetch_assoc($fetch1)){
$variants_array = explode(',', $row["variants"]);
$vari_array = array();
foreach($variants_array as $var){
$var = explode(':',$var);
$vari_array[$var[0]] = $var[1];
}
$json['products']['specification']['variants'] = $vari_array;
//array_push($json['products'],$row_temp);
}
echo Json_encode($json);
?>
and output of this is
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": {
"size": "long"
}
}
}
}
but in this i have one more value for variant i.e.
"size":"small" and that is not showing up.
sorry for bad English please ask me for any clarification before answering
my desired output
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": {
"size": "small"
"size": "long"
}
}
}
}
You can't add same key size twice. The previous key gets overwritten by later.
Since you are repeating the key size again the values are being overwritten. Pass all the required values which are belonging to the same Key in an array.
yes you cant use same key name ..
you can get like
{
"products": {
"product_id": "1",
"product_name": "Face Wash",
"specification": {
"brand": "Python",
"product_Description": "very good",
"variants": [{"size": "small"},{"size": "long"}]
}
}
}
You can do '$vari_array[$var[0]][] = $var[1];' now the size is multidimensional array.
as shown by https://stackoverflow.com/users/1993125/wisdmlabs in comments