need to get json format from php - php

I am getting a json format like this
[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}]
from code
$rt = array();
$rt["service"]["title"] = karthik;
$rt["service"]["city"] = chennai;
$t = array();
$t["service"]["title"] = siva;
$t["service"]["city"] = madurai;
echo json_encode(array($rt,$t));
but i need the same format of json result from this code
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
}
echo json_encode(array($jsonresponse));
but the result actually i get from the above code is
[{"service":{"title":"Event Help","city":"Santa Fe"}}]
please someone help me on this issue.....

Use an array store all the values returned from the query
$array = array();
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
$array[] = $jsonresponse;
}
echo json_encode(array($array));

you are overwriting $jsonresponse in your while loop, you should add this into array and json_encode this array
$response = array();
while( ... ){
...
$response[] = $jsonresponse;
}
echo json_encode($response);

try like this
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id FROM
task");
$jsonrow=new stdClass;
$jsonresponse=new stdClass;
while($row=mysql_fetch_array($a)) {
$jsonrow->title=$row['title']; $jsonrow->city=$row['city'];
$jsonresponse->service=$jsonrow;
}

Related

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

Push array into array then encode - PHP

I'm trying to combine a few mySQL queries in a single PHP and push it all into a single JSON object.
So, I'm starting with the first query...like this:
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
$data['count'] = $final_count;
If I then do echo json_encode($data); I get a nicely formatted object like: {"count":61}
I then have a second query that I put the results through a loop, like so:
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach ($response as &$value) {
$items[] = $value['date_added'];
}
echo json_encode($items);
And I get my nice set of dates:
["2017-06-24 00:08:58","2017-06-26 15:01:48","2017-06-27 15:01:48","2017-06-28 23:19:41","2017-06-29 01:38:07","2017-06-30 00:08:58"]
Here's the question, how do I get this all back together like so:
{
"count": 61,
"dates": [
"2017-06-24 00:08:58",
"2017-06-26 15:01:48",
"2017-06-27 15:01:48",
"2017-06-28 23:19:41",
"2017-06-29 01:38:07",
"2017-06-30 00:08:58"
]
}
You could use
$myData['count'] = $final_count;
$myData['dates'] = $items
echo json_encode($myData);
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
// first store count in `$data`
$data['count'] = $final_count;
$data['dates'] = [];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
// next, store dates in subarray of `$data`
foreach ($response as &$value) {
$data['dates'][] = $value['date_added'];
}
// finally encode everything
echo json_encode($data);
Of course you can use array_merge of all your collected data.
Or:
$data=[];
// get $final_count
$data['count'] = $final_count;
// ... do some more stuff
// load items from db
$data['dates'] = $items;
echo json_encode($data);

trouble with array push in php

I have a problem with array push.I cant get the all data from the array array.I want to get like this format.
[["username","average"],["aa",2.34],["bb",6.7],["hh",9.8]]
here is my code
while($acc_rs = mysql_fetch_array($acc_qry))
{
$acc_cnt = $acc_rs['Total_login'];
$time_stamp = $acc_rs['last_logged'];
$avg_login = $acc_rs['avg'];
$name = $acc_rs['name'];
$ji = array();
$sal = array("username","average");
$kk = array($name,$avg_login);
array_push($ji,$sal,$kk);
}
array_push($da,$new,$average);
$result = array(array('username', 'average'));
while ($row = mysql_fetch_assoc($acc_qry)) {
$result[] = array($row['name'], $row['avg']);
}
echo json_encode($result);

add php function to json array before encoding

$selected_offer = $_POST['selected_offer'];
$get_categories = $db->query("SELECT oc_id, oc_name FROM object_category WHERE oc_relate = '".$selected_offer."'");
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$json[] = $get_rows;
}
echo json_encode($json);
return;
I toke this code from someone else and since I am not familiar with json I am asking here at stackoverflow how can add a function to the oc_name attribute before the json encodes it and still return the same struckture as it is now, like for example:
language($get_rows['oc_name'])
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name'] = language($get_rows['oc_name']);
$json[] = $get_rows;
}
You can apply your function on the mentioned field before you add the row in your $json array
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name']=language($get_rows['oc_name']);
$json[] = $get_rows;
}

Array declared outside and inside loop gives different result in php mysql

Why will my array have different output within the while loop, like it fetch all data from database in json, but once I declare the array outside of the while loop as commented out it gives output single row in json? Am I missing something basic or what? Thanks in advance
$query = "SELECT * from creative ORDER BY rand()";
$rs = mysql_query($query);
//$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
$arr[] = $obj;
$cid = $arr -> id; //get id
}
if (isset($imei) && !empty($imei)) {
$add = array('delay'=>"1800000"); //Add Objects to JSON Encoded Array
$arr[] = $add;
echo json_encode($arr);
Have you tried array push?
$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
//$arr[] = $obj;
array_push($arr, $obj);
//$cid = $arr -> id; //get id
}

Categories