output json array in php - php

I have this json currently :
{"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}
I was wondering how I could output this :
{"quests": {"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}
}
Here is the code in php:
while($result=mysql_fetch_array($number, MYSQL_ASSOC)){
print(json_encode($result));
}

Try this:
$result = array('quests' => array());
while($row = mysql_fetch_array($number, MYSQL_ASSOC)){
$result['quests'][] = $row
}
echo json_encode($result);

If I understand correctly what you are trying to do, get a JSON packet with all the rows, then loop over them to put them in an array, then encode the whole array:
<?php
$result = mysql_query($query);
$out = array('quests' => array());
while ($row = mysql_fetch_assoc($result)) {
$out['quests'][] = $row;
}
print json_encode($out);
?>

Related

output an array using PHP

I have the following PHP code:
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
I fetch all the data with the column name "name" in database. How can I output it like this?
["John", "Doe", "Deer"]
You have to make $data as array type variable.
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // required output
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // output key wise display like
Array ( [0] => John [1] => Doe ) etc.
But output as you suggestion then just add json_encode()
print_r(json_encode($data)); // output like
["John", "Doe", "Deer"]
$data = [];
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
echo json_encode($data); // or you can use print_r for debugging.
You need to use json_encode() method to your array to be accepted in your jquery. Rearrange the code like following..
$data = array();
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
$new_array = json_encode($data);
echo $new_array; // use 'echo' to print. The json_encode() convert $data array to string.

PHP - How to merge two different JSON outputs into one

My php server is generating two JSON output
1.] For MySql JSON printing I am using this code.
$sql = "select id ,Title , Meassage from lodhinews";
$result = $conn->query($sql);
$values = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$values['data'][] = array(
'id'=>$row['id'],
'Title'=>$row['Title'],
'Meassage'=>$row['Meassage']
);
}
header('Content-Type: application/json;charset=utf-8');
echo json_encode($values ,JSON_PRETTY_PRINT);
} else {
$values = array(
'error'=>'No results found'
);
}
$conn->close();
?>
2.] For file name printing I am using this code
chdir('./uploads');
foreach(glob('*.*') as $filename){
$data[] = $filename;
}
echo json_encode($data);
?>
both the above code is working fine!
I wanted this both json output combined on one single page
not very complicated ! :)
$merged_array = array();
$merged_array[] = $data;
$merged_array[] = $values;
print json_encode($merged_array,JSON_PRETTY_PRINT);

json_encode() error output when i do an while loop to fetch the results in a array

from this php while loop i fetch the results in a array
$rows = array();
$result = mysqli_query($con,"call getProductVariationByID($name)");
//$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_assoc($result))
{
$rows['Product'][] = $row;
}
echo json_encode($rows, JSON_PRETTY_PRINT);
the result is with this 'null' in the end :
"post_mime_type": "",
"comment_count": "0"
}
]
}null
I bet the function containing this code is echo'd in your main php script.

Json encode an entire mysql result set

I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

Categories