create array of objects in php - 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".

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

json_encode multiple arrays into one JSON object in 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);

2 select query in different array on one json object

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

PHP generate JSON in certain format

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

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