Add Additional Objects in JSON - php

I am currently using a JSON encoded array to display the title in my database for an auto-suggest feature.
It looks something like this:
<?php
require_once('./includes/config.php');
require_once('./includes/skins.php');
mysql_connect($conf['host'], $conf['user'], $conf['pass']);
mysql_select_db($conf['name']);
$query2012 = sprintf("SELECT * FROM imdb WHERE poster !='posters/noposter.jpg' ORDER BY RAND() DESC LIMIT %d;", 8);
$result = mysql_query($query2012);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['title'] = $row['title'];
$row_array['year'] = $row['year'];
$row_array['poster'] = $row['poster'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
This returns:
[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"status":"ok","message":"Success","data":
{"status":"ok","message":"Success","data":[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]}
and if mysql record not found show json output
{"status":"error","message":"No Reord found"}
how i can add this ?

You can add this to your $json_response array before encoding (json_encode() by modifying it structute:
$json_response = array(
'data' => $json_response,
'status' => 'ok',
'message' => 'Successs'
);
You can also modify appending data to your final result variable so while you define your $json_response array add subarray:
$json_response = array('data' => array());
and in while loop add index data:
array_push($json_response['data'], $row_array);
And after loop you can easily append your status and message by:
$json_response['status'] = 'ok';
$json_response['message'] = 'Success';
To add error just check if the data array is empty. For first solution:
if (empty($json_response)) {
$json_response = array(
'status' => 'error',
'message' => 'No Reord found'
);
} else {
// here append success message
}
In second case just change a if condition to:
if (empty($json_response['data']))

Related

php file that returns a string json encode didnt work

I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );

pass variables not in database row through json array

I have a bit of code I would like to pass through my json array that is not contained in the database $row. So i tried to set a custom variable and that didn't work. Is there a way to do this so the below content gets sent through with the array?
Here is what I tried
PHP
if ($photo_numff == 1) {
$streamitem_uploadimage_count =" Uploaded new image";
} else if($photo_numff > 1) {
$streamitem_uploadimage_count =" Uploaded ".$photo_numff." new images";
} else {
}
JSON array
$rowcount = mysqli_num_rows($result);
$json = array(
'posts' => array(),
'count' => $rowcount
);
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
//Post information and ids
'streamitem_id' => $row['streamitem_id'], // post id
'streamitem_uploadimage_count' => $streamitem_uploadimage_count,
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);
I can then take this through my ajax "+response['streamitem_uploadimage_count']+"
I have also tried array_push($json['posts'], array( 'streamitem_uploadimage_count' => $streamitem_uploadimage_count, ) );but doesn't work
I have now got this working by adding
'streamitem_uploadimage_count' => $streamitem_uploadimage_count
within the $Json array also.

How to properly encode a multi-dimensional array in php [duplicate]

This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 7 years ago.
I am trying to properly create and encode and array using json_encode php function. The array i am trying to encode is $myarray . From my code if do
$myarray = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
then
echo json_encode($myarray) ; // this works but only one item is pushed to my array
if i do
$myarray[] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array
result is nothing.
what i am missing ?
see full code below on what i have so far done.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
//Push values to my array
$myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
//
}
//Then try to encode $myrray but this fails
$jsonstring = json_encode($myarray);
if ($jsonstring!==false)
{
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
///////////////////////
/////////////////////////
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
please help. thank you.
The right way to create the array would be like this:
$myarray = array(
array(
'name' => 'bla',
'id' => 1
), array(
'name' => 'blas',
'id' => 2
)
);
This part of your code is perfectly fine.
$data = array() ; //create new empty array
//loop through the array
foreach($myarray as $keys => $h)
{
$data [] = $h;
}
//encode
echo json_encode($data) ; //this fails silently
If you run the code, it works perfectly fine:
[{"name":"bla","id":1},{"name":"blas","id":2}]
Your foreach() loop creates a new array $data with the same entries (also arrays) as the $myarray contains. So, you could directly encode $myarray like this:
<?php
$myarray = array(
array('name' =>' Agrolait', 'id' => 6 ),
array('name' => 'Agrolait, Michel Fletcher', 'id' => 31 ),
array('name' => 'Agrolait, Thomas Passot', 'id' => 30 )
);
$jsonstring = json_encode($myarray);
if ($jsonstring!==false) {
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
?>
Which produces this JSON string:
[{"name":" Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}]
json_encodereturns the value FALSE if something went wrong, and the encoded string else. If you check the result from it you at least know when it fails.
Thanks for your suggestion have solved this. My string data was not properly encoded using utf-8 as suggested by http://nl3.php.net/manual/en/function.json-encode.php. Check my answer below
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
$myarray [] = array('name' =>utf8_encode($value['display_name']->scalarval()),'id' => utf8_encode($value['id']->scalarval())) ;
//
//array_push($better, $myarray) ;
}
//echo '<pre>';
//print_r($myarray) ;
//echo '</pre>';
echo json_encode($myarray);
exit;
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

PHP why does this only output 1 row?

$responses = array();
while ($row = mysql_fetch_array($result)) {
$response = array(
'name' => $row['name']
);
$row;
$responses['name5'] = $response;
}
echo json_encode($responses);
I'm currently only getting 1 rows from this statement I know for a fact their are more.
On each iteration of your while loop, you are overwriting the same array key $responses['name5'], so in the end you'll only have one value in the $responses array.
Instead, you might want something like this to append to the end of the array:
$responses[] = $response;
you are overwriting the $response variable that's why, array_push instead
$responses['name5'] = $response;
You will get only last row because you replace your data each cycle step.
Try this:
$responses['name5'][] = $response;
Because you're resetting the $response array to a single array in the loop. You want to add to the array.
$responses = array();
while ($row = mysql_fetch_array($result)) {
array_push($response, array(
'name' => $row['name']
));
$row;
$responses['name5'] = $response;
}
echo json_encode($responses);
do
$responses[] = array('name5' => $response);

Categories