json_encode multiple arrays into one JSON object in PHP? - php

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

Related

How would I be able to create brackets around my json file using PHP?

function get_data()
{
$connect = mysqli_connect("localhost", "root", "root", "Database");
$query = "SELECT * FROM Furniture";
$result = mysqli_query($connect, $query);
$categories = array();
$row = mysqli_fetch_array($result);
{
$categories[] = array(
'mapwidth' => "2000",
'mapheight' => "2000",
);
}
This is what I have so far, but how would I be able to create an array of "categories" so that the json file looks like this,
{
"mapwidth": "2000",
"mapheight": "2000",
"categories": [
{
"id": "furniture",
"title": "furniture",
"color": "#4cd3b8",
"show": "false"
},
{
"id": "rooms",
"title": "Rooms",
"color": "#63aa9c",
"show": "true"
}
],
I tried to do this but I was only able to get one row to display but am not sure how to iterate through the database so that every row will display the "id", "title", "color", and "show" within the brackets as seen in the json file. So I pretty much just want the json file to look exactly like the one shown here.
Try it like this:
$employee_data = array();
$categories = array();
$employee_data["mapwidth"] ="2000";
$employee_data["mapheight"] ="2000";
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$categories[] = $row;
}
$employee_data["categories"] =$categories;
echo json_encode($employee_data);
Refer to this answer to further improve your code.

How to encode multiple json elements using PHP?

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

Json Parsing error using JSON.parse()

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();
}

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.

PHP code to get the json output in the following format

Hi i have written an android app which interacts with php to get data from the database.
I need the json to return the data back in this format.
[
{
"outlet_id" :"1",
"outlet_desc" :"BigBazaar",
"outlet_loc" :"Jayanagar4thBlock",
"outlet_image" :"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FBigBazaar.png",
"recommended_products": [
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
}
]
},
{
"outlet_id":"2",
"outlet_desc":"FoodWorld",
"outlet_loc":"Basavanagudi",
"outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FFoodWorld.png","
recommended_products":[
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
},
{
"item_id":"3",
"item_desc":"Colgate",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"
}
]
},
{
"outlet_id":"5",
"outlet_desc":"Total",
"outlet_loc":"MurgeshPalaya",
"outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FTotal.png",
"recommended_products":[
{
"item_id":"3",
"item_desc":"Dettol",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
},
{
"item_id":"3",
"item_desc":"Colgate",
"item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"
}
]
}
]
But right now it is giving in the following format.
[
[
{
"outlet_id": "1",
"outlet_name": "Big Bazaar",
"lat": "12.9285690",
"lng": "77.5831100",
"outlet_image": "images/BigBazaar.png",
"outlet_location": "Jayanagar 4th Block"
}
],
[
{
"outlet_id": "2",
"outlet_name": "Food World",
"lat": "12.9392350",
"lng": "77.5780680",
"outlet_image": "images/FoodWorld.png",
"outlet_location": "Basavanagudi"
}
],
[
{
"outlet_id": "5",
"outlet_name": "Total",
"lat": "12.9589340",
"lng": "77.6571610",
"outlet_image": "images/Total.png",
"outlet_location": "Murugeshpalya"
}
],
[
{
"outlet_id": "6",
"outlet_name": "Big Bazaar",
"lat": "12.9324963",
"lng": "77.6228463",
"outlet_image": "images/BigBazaar.png",
"outlet_location": "Koramangala"
}
],
[
{
"outlet_id": "7",
"outlet_name": "Food World",
"lat": "12.9785055",
"lng": "77.6379353",
"outlet_image": "images/FoodWorld.png",
"outlet_location": "Indira Nagar"
}
]
]
This is my php code.
<?php
error_reporting(0);
//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
//$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
while($row = mysql_fetch_assoc($result))
{
$output[] = array($row);
}
print( json_encode($output) );
?>
How can i modify the above php code to return in the 1st format. Please help as i am not so good in php.
Table Structure.
Outlets Table.
It contains the following fields.
outlet_id outlet_name lat lng outlet_image outlet_location
Recommendations table.
It contains the following fields.
item_id outlet_id
Items table.
It contains the following fields.
item_id item_name item_image item_price category_id
Ok so it's the missing sub-array. You want to create a JSON string, not a object, from a multidimensional associative array.
There are faster ways to select these rows but this is easy to follow.
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
$output=array(); # don't leave it undefined
while($row = mysql_fetch_assoc($result))
{
# guessing this query
$query2 = "SELECT * FROM recommended_products WHERE outlet_id=".$result['outlet_id'];
# now we create the sub array recommended_products
$row['recommended_products']=array();
$result2 = mysql_query($query2) or die("Unable to verify user because : " . mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
$row['recommended_products'][]=$row2;
}
# then add the modified row to the output
$output[] = $row;
}
print( json_encode($output) );
Also, mysql_ is depreciated. Probably no genuine need to rush but it's worth at least looking at converting to mysqli or PDO.
Change $output[] = array($row); to $output[] = $row;

Categories