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);
Related
I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);
Can anyone explain me how to get the final value assigned to variable after completing executing while loop?
In my below code I wanted to echo the response out of while loop after fetching all the values from the rows.
Because if I put echo out of while loop it only shows 1st record.
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
echo $response;
}
You will get the last rows value into the $response.
Cause: Every time the loop executes will assign value into the variable. But as you echo it you can see all the values as output.
So what you really need to do is storing the values in an array...
$response = array();
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
print_r($response);
If you need further information about this , just let me know.
Since you are doing variable assignment and echo inside while loop, it will not serve your purpose.
You have to do it like below:-
$response = array(); // create an array
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load(); // assign each value to array
}
echo "<pre/>";print_r($response);// print the array
Note:- this array will have all the values now. You can manipulate it in your desired way.Thanks
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
}
echo $response;
Try this:
$response = [];
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
var_dump($response);
I am doing my project in codeigniter. My issues is i will store value for 'game_aspect_details' in json format like
"{"game_aspect_details":[{"aspect_id":"1"},{"aspect_id":"4"}]}"
for this select query i will decode the json format and check that value in foreach.
$this->db->select('game_aspect_details');
$this->db->from('share_reviews');
$this->db->where('review_id',6);
$query = $this->db->get();
$result = $query->result();
$test = $result[0]->game_aspect_details;
$res = json_decode($test);
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row->game_aspect_details); //here i need
$query1 = $this->db->get(); to check 1 and 4
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
print_r($res);
exit;
First this do see what you are getting in the $row within the foreach by using the print_r().
And I hope that you need to replace the below line
$this->db->where('game_aspect_id',$row->game_aspect_details);
With following line:
$this->db->where('game_aspect_id',$row['aspect_id']);
as $row is an array not an object.
EDITED:
foreach ($res as $rows)
{
foreach ($rows as $row)
{
........
$this->db->where('game_aspect_id',$row['aspect_id']); //here make change
.....
}
}
You are doing some things wrong, see the comments in this code:
...
//$test = $result[0]->game_aspect_details; // This does not work since $result is not decoded yet
$res = json_decode($result); // Changed to `$result` instead of `$test`
$res = $res->game_aspect_details; // Instead pick the `game_aspect_details` here, after the decode
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row['aspect_id']); // Changed to `aspect_id`
$query1 = $this->db->get();
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
...
I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;
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;
}