PHP generate JSON in certain format - php

So i want to generate my JSON for a angular app in this format. The result will be used for a dropdown and i need it to be in this particular format
[
{
id:1,
post_title:title1},
{
id:2,
post_title:title1},
{
id:3,
post_title:title3},
and so on ...
]
But when i send my JSON back to my angular app it looks like this
{
"0": {
"id": "1",
"post_title": "Batman Ipsum"
},
"1": {
"id": "2",
"post_title": "Title fit for a (precariously enthroned) king"
},
"2": {
"id": "3",
"post_title": "Cupcake Ipsum"
},
"3": {
"id": "4",
"post_title": "The most presidential lorem ipsum in history."
},
"4": {
"id": "5",
"post_title": "Quote Ipsum"
},
"5": {
"id": "6",
"post_title": "Yet another Batman Ipsum"
},
"6": {
"id": "9",
"post_title": "Yet another Harry Potter ipsum"
},
"7": {
"id": "10",
"post_title": "Vegetable Ipsum"
}
}
How to change it to the format that i want?
My php code
function fetchPagesNames()
{
$response = array();
$resultArray=array();
try {
$sql = "SELECT id,post_title FROM posts";
$result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
$resultCount = mysql_num_rows($result);
if ($resultCount > 0) {
while ($row = mysql_fetch_assoc($result)) {
$resultArray[]=$row;
}
$response['status'] = 'Success';
$response['message'] = "Post's Obtained";
$response['results'] = $resultArray;
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
echo json_encode($response,JSON_FORCE_OBJECT);
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}
}
What changes are needed?

There are two major differences between your "required" format and the output you're getting:
The format you've quoted as being required is not actually valid JSON because you're missing the quotes.
The JSON format is very explicit in that it must have quotes around property names and string values. The JSON you're getting outputted is correct in this regard.
Your required output has an outer layer that is an array, whereas your actual output has an object, with numbered elements as strings.
The reason for this is because you're using JSON_FORCE_OBJECT in your call to json_encode(). This argument forces all parts of the JSON otput to be processed as objects not arrays. Remove this and you'll get the top-level array that you're looking for.

Remove JSON_FORCE_OBJECT from json_encode().

Use json_encode for print object.
or look like this...
try {
$sql = "SELECT * FROM tekst";
$result = $dao->conn->query($sql);
//$resultCount = mysql_num_rows($result);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode(
$resultArray
);
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}

Related

How to get data in json form

Currently, I am making an API and I want the data in JSON format. But I am not able to get it. It is coming in normal form. But how to convert it into JSON. If I am writing json_encode($response) outside the loop then I am getting the data in json format but only one data.
If i wriing the json encode inside the loop then i am getting all the data but not in JSON form. How to solve this. I am not able to get the perfect solution for ths question.
$tsym = strtolower($_REQUEST['tsym']);
$time = strtolower($_REQUEST['time']);
$mil = $time;
$seconds = $mil / 1000;
$normal_date = date("Y-m-d H:i:s", $seconds);
$sql = "SELECT * FROM `forex` where pair='".$tsym."' and date >= '".$normal_date."' order by date limit 0,10";
$result = mysqli_query($conn, $sql);
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
//if(!isset($response[$from_sym]))
{
$response[$from_sym] = $rows;
//echo json_encode($response, true);
//}
print_r( json_encode($response)); //this prints all the data but not
in json form
}
print_r( json_encode($response)); //this prints single data but in
json form
I want all the data but in json form. how to get it? Thank you for the help.
I want data like this:
{
"CHFJPY": {
"id": "33",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:21",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "75",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:29",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "117",
"pair": "CHFJPY",
"date": "2018-04-23 11:25:47",
"price": "110.585",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "159",
"pair": "CHFJPY",
"date": "2018-04-23 12:34:54",
"price": "110.816",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "201",
"pair": "CHFJPY",
"date": "2018-04-23 12:35:04",
"price": "110.825",
"change_rate": "0",
"fetched": "1"
}
}
But i am getting only one data.
You have to append your row to the final array $response in your while loop
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
$res[$from_sym] = $rows;
$response[] = $res;
}
print_r(json_encode($response));
You need to move the json_encode into the outside of while loop
<?php
$tsym_escaped = mysqli_real_escape_string($conn, $_REQUEST['tsym']);
$date = date("Y-m-d H:i:s", $_REQUEST['time']/1000);
$sql = sprintf(
"SELECT * FROM `forex` WHERE `pain`='%s' AND `date`>='%s' ORDER BY `date` LIMIT 0,10",
$tsym_escaped,
$date
);
$result = mysqli_query($conn, $sql);
$response = array();
while($row = mysqli_fetch_assoc($result)){
$response[$row['pair']] = $row;
}
echo json_encode($response);
Also, the way you're passing the data into the SQL query is insecure and can lead into a SQL injection.
is not clear why you have not json so .. in more clear way try
while($rows = mysqli_fetch_assoc($result)){
$response[$rows['pair']] = $rows;
}
$myJSON = json_encode($response);
var_dump($myJSON);
this should buil a $reponse array with the related vleus for each 'pair' index
but could be you need all the rows result so try
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows;
}
$mySecondJSON = json_encode($response);
var_dump($mySecondJSON);
or
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows['pair'];
}
$myOtherJSON = json_encode($response);
var_dump($myOtherJSON);

create array of objects in php

Im trying to create and array of objects in php to send to my AngularJS app the format want is
[
{},
{},
{}
]
but when i run my code i get an outer array and a inner array and the objects are inside the inner array..i dont want 2 arrays just a single outer level array
heres what im getting
[
[
{
"id": "16",
"post_title": "Gotta love Batman",
"author_name": "Clinton Dsouza",
"publish_date": "Tuesday, October 13th 2015, 4:50:50 pm"
},
{
"id": "15",
"post_title": "Web 2.0 ipsum...Again",
"author_name": "Clinton Dsouza",
"publish_date": "Tuesday, October 13th 2015, 4:48:42 pm"
},
{
"id": "10",
"post_title": "Vegetable Ipsum",
"author_name": "Clinton Dsouza",
"publish_date": "Tuesday, October 13th 2015, 1:36:57 pm"
},
{
"id": "9",
"post_title": "Yet another Harry Potter ipsum",
"author_name": "Clinton Dsouza",
"publish_date": "Tuesday, October 13th 2015, 1:28:55 pm"
}
]
]
as u can see there's an array inside an array..how do i go about fixing this to obtain the format i want
my code
try {
$resultArray = null;
$sql = "SELECT id,post_title,author_name,publish_date FROM posts ORDER BY id DESC LIMIT 4 OFFSET $data->offset ";
$result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
$count = mysql_num_rows($result);
$index = 0;
if ($count > 0) {
while ($row = mysql_fetch_assoc($result)) {
$resultArray[$index]=new StdClass();
$resultArray[$index]->id = $row['id'];
$resultArray[$index]->post_title = $row['post_title'];
$resultArray[$index]->author_name = $row['author_name'];
$resultArray[$index]->publish_date = $row['publish_date'];
$index++;
}
$response['status'] = 'Success';
$response['message'] = 'Data present';
$response['results'] = $resultArray;
} else {
$response['status'] = 'Error';
$response['message'] = 'No Posts found';
}
echo json_encode($response);
} catch (Exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}
When you use json_encode it automaically converts array to objects i.e javascript object notation ..No need to manipulate .Only you have to do it as --
if ($count > 0) {
while ($row = mysql_fetch_assoc($result)) {
$resultArray[]=$row;
}
One way to fix it is: You could index in the array (to get the array in the array) and store its value in a new variable. This way you will get rid of the "double array".

How to place the json objects into array usin php?

this is my php code, to obtain json format data
if($status==1)
{
$post_id=$json_object['post_id'];
$get_postid=mysqli_query($con,"select * from User_Post where post_id='$post_id'");
if(mysqli_num_rows($get_postid)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists."));
}
else
{
foreach($field_check as $values)
{
if($values=='id')
{
$row_array = array();
while ($row = $get_postid->fetch_array())
{
$row_array['id']=$row['post_id'];
$row_array['image_urls']=explode(',',$row['post_image_url']);
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
}
elseif($values=='tagged_users')
{
while ($row = $get_postid->fetch_array())
{
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
for($i=0;$i<count($storetag);$i++)
{
$user=mysqli_query($con,"select user_id, profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
}
else
{
while ($row = $user->fetch_array())
{
$tagged_users[$i]['user_id']=$row['user_id'];
$array['user_id']=$tagged_users[$i]['user_id'];
$pro_image_url[$i]=$row['profile_image_url'];
$short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
$short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
$array['short_image_url']=$short_image_url[$i];
}
}
array_push($row_array,$array);
}
}
}
array_push($json_response,$row_array);
echo str_replace('\/','/',json_encode($json_response));
}
}
It is returning the following objects
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
}
]
but i want to assign name to that array like this
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"tagged_users":[
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
]
}
i don't know where i have to add this array name. Please help me solve this.
I can't assign the array name like this because $row_array also contains other data
echo str_replace('\/','/',json_encode(array("tagged_user"=>$json_response));
On second to last line this should be what you wanted:
array_push($json_response,array("tagged_users" => $row_array));
Edited to remove second part.
Try with -
array_push($row_array['tagged_users'],$array);
Or define it like -
$row_array['tagged_users'] = array();
Then all the values will be as you want.

Json_Encode php last comma

For a school project I have to display database data as a valid json file.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
echo "{ \"films\" : [";
while ($row = mysqli_fetch_array($result)) {
$jsonResult = json_encode($row);
echo $jsonResult;
echo ",";
}
echo "]}";
The output i get is:
{
"films": [
{
"0": "Man on fire",
"titel": "Man on fire",
"1": "Actie",
"genre": "Actie"
},
{
"0": "Dumb and Dumberer",
"titel": "Dumb and Dumberer",
"1": "Comedy",
"genre": "Comedy"
},
{
"0": "DefQon 2014",
"titel": "DefQon 2014",
"1": "Muziek",
"genre": "Muziek"
},
]
}
Now my question is, how do I remove the last comma, I cannot find that. And all data tells the data 2 times, I also don't know how to avoid this.
Let json_encode handle the entire thing - build one array of data, and use json_encode on that.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
$response = array();
$response['films'] = array();
while ($row = mysqli_fetch_array($result)) {
$response['films'][] = $row;
}
echo json_encode($response);
A good way to do this, is to not place a comma after writing every record, but instead before every record.
Then all you have to do, is add an if statement that doesn't output the comma for the very first row.

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

Categories