json_encode format in codeigniter - php

With my present code I get the right details from my dbase with json_encode.
[{
"tour_id": "1",
"tour_name": "Test this",
"start": "2016-01-12 13:21:32",
"end": "2016-01-15 13:21:35",
"itinerary_photo": "Desert.jpg"
}][{
"tour_id": "3",
"tour_name": "Everest",
"start": "2016-02-10 13:23:00",
"end": "2016-02-18 13:23:07",
"itinerary_photo": "Chrysanthemum.jpg"
}]
EXPECTED JSON FEED
I am using a json feed in order to add an event to fullcalendar. And the format of my json_encode results should be like this:
[{
"tour_id": "1",
"tour_name": "Test this",
"start": "2016-01-12 13:21:32",
"end": "2016-01-15 13:21:35",
"itinerary_photo": "Desert.jpg"
}, {
"tour_id": "3",
"tour_name": "Everest",
"start": "2016-02-10 13:23:00",
"end": "2016-02-18 13:23:07",
"itinerary_photo": "Chrysanthemum.jpg"
}]
the difference being the objects are stored into one array only. With the output im getting, it displays multiple arrays.
here is my code for the controller:
public function getBookedCal(){
if ($this->session->userdata('login')==true){
$data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
echo json_encode($tourConfirm);
}
//echo json_encode($tourConfirm); //this outputs only a single array
}//end if
}//end function
MODEL:
function getPaidTours($user_id){
$this->db->where('User_accounts_user_id',$user_id);
$this->db->where('payment_status','1'); //confirmed
$query = $this->db->get('user_tourpkg');
return $query->result_array();
} //calendar
function getTourInfo($tour_id){
$this->db->select('tour_id,tour_name, start, end, itinerary_photo');
$this->db->where('tour_id',$tour_id);
$query = $this->db->get('tour_packages');
return $query->result();
}
is there any way i could obtain my expected json feed with some tweaks to my code?

Instead of using variable use array, don't use foreach value as assign value
$tmptourConfirm = array();
foreach ($data['tour'] as $tourConfirm){
$tmptourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
echo json_encode($tmptourConfirm);

you have to declare $tourConfirm as array before for each loop and encode that array into json after loop.
E.g.
public function getBookedCal(){
if ($this->session->userdata('login')==true){ $tmptourConfirm = array(); $data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
echo json_encode($tourConfirm);
}//end if
}/

Change getBookedCal() as follows,
public function getBookedCal(){
$tourConfirm = array();
if ($this->session->userdata('login')==true){
$data['twimembers'] = $this->session->userdata('twimembers');
$data['tour'] = $this->Model_MyBookedTours->getPaidTours($data['twimembers']['user_id']);
foreach ($data['tour'] as $tourConfirm){
$tourConfirm[] = $this->Model_MyBookedTours->getTourInfo($tourConfirm['Tour_packages_tourpkg_id']);
}
//echo json_encode($tourConfirm); //this outputs only a single array
}//end if
echo json_encode($tourConfirm);
}//end function

Related

Loop json object as array in PHP

How can i loop the response to get all ids and names?
If the response like this:
{
"Data": [
{
"Id": "4321",
"Name": "Dog"
},
{
"Id": "749869",
"Name": "Cat"
}
]
}
I can get all the ids and names using this code:
foreach (json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
But, if the response like this:
{
"Data": {
"dog": {
"Id": "4321",
"Name": "Dog"
},
"cat": {
"Id": "749869",
"Name": "Cat"
}
}
}
How can i get all the ids and names without knowing the amount of the array? Thank you.
You can get PHP to read everything into an (associative where applicable) array.
foreach (json_decode($response->content, true)["Data"] as $resp) { //2nd parameter is to decode as array
echo $resp["Id"];
echo $resp["Name"];
}
Example run: https://eval.in/954621
Alternatively you can do the lazy thing and just cast:
foreach ((array)json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
Well if you want to extract all ids into one array (I assume you mean all into one array), to use in a database query as an example. I would recommend you doing like this.
$ids = array_values(array_map(function($animal){
return intval($animal['Id']);
}, json_decode($response->content, true)['Data']));
var_dump($ids);
you do the same ! foreach loop would work on both.
the json response supposed to have the same format every time, unless you have a really weird API.
<?php
$response = json_decode($json);
foreach($response as $animal => $data)
{
echo $animal;
echo $data->id;
echo $data->name;
}

How to get json format for monogo db object [duplicate]

I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;
$customers = $db->customer->find();
i want to return $customers collection as json document to my HTML. How can i do this?
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.
This also will work. And you can customize your json as well.
$arr = array();
foreach($customers as $c)
{
$temp = array("name" => $c["name"], "phone" => $c["phone"],
"address" => $c["address"]);
array_push($arr, $temp);
}
echo json_encode($arr);
Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
"5587d2c3cd8348455b26feab": {
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
"5587d2c3cd8348455b26feac": {
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
}
So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);
This creates the same result as
$result = Array();
foreach ($customers as $entry) {
array_push($result, $entry);
}
echo json_encode($result, true);
which is an array of JSON objects
[
{
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
{
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
]

PHP - Append new JSON object to nested array within JSON object

Setup
I have retrieved a JSON string from a URL using 'file_get_contents' and have subsequently decoded it using `json_decode'
$search_URL="http://abcdefg.com"
$json = file_get_contents($search_URL);
$obj = json_decode($json, true);
The JSON represents an Apache Solr search response:
{
"responseHeader":{
"status":0,
"QTime":3,
"params":{
"q":"zzzzzzz",
"wt":"json"
}
},
"response":{
"numFound":20690,
"start":0,
"docs":[
{
"title":"yyyyy-y-y-yyyyy-yy-y",
"author":"author 1, author 2, author 3",
"url":"https://yyyyy.com",
"id":yyyy,
"_version_":yyyyy
},
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx
},
]
}
}
I basically need to grab each author field in the docs[] array, split it by commas to get a new array
$author_array = explode(", ", $author);
I then need to call another web service with these author names that will return JSON. I would love to simply plug this JSON in to my existing JSON and send it all back
Question
I need to modify my JSON so that each doc contains this new JSON object. How can I do this?
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
{
"name": "author1",
"id": "143"
},
{
"name": "author2",
"id": "72"
}
]
}
My Attempt
I have tried a simpler version of this where I simply have an array of author names
{
"title":"xxxx-x-x-xxxx-xxxx",
"author":"author 1, author 2",
"url":"https://xxxxx.com",
"id":xxxxx,
"_version_":xxxxxx,
"authors":[
"author1",
"author2"
]
}
I tried the following:
$response = $obj['response'];
$docs = $response['docs'];
foreach($docs as &$doc) {
$author = $doc['author'];
$authors_array = explode(" ,", $author);
$doc['authors'] = $authors_array;
}
This has ultimately failed as the new array is not appended.
Explode the author string, call the API on each element, make an array of all these results, and put it back into the object.
I use a reference below in foreach so it can modify the document element directly.
foreach ($obj['response']['docs'] AS &$doc) {
$author_names = explode(',', $doc['author']);
$author_array = array_map('author_api', $author_names);
$doc['authors'] = $author_array;
}

Trying to fetch Json Result

I am trying to fetch the individual values from the obtained json result
{
"_total": 1,
"values": [{
"id": 123456,
"name": "Example Technologies "
}]
}
Now, I need to get the _total value. For that i am using
echo $res->_total;
which gives me
Notice: Trying to get property of non-object
If i try like
echo $res['_total'];
gives me
Warning: Illegal string offset '_total'
So, In what way, I can get the _total value.
Please help me in that. Thanks in advance!
Do this:
$obj = json_decode($res);
echo $obj->_total;
You need to decode the JSON data.
suppose data is
$data = '{"category_id":"10","username":"agent1","password":"82d1b085f2868f7834ebe1fe7a2c3aad:fG"}';
and you want to get particular parameter then
$obj = json_decode($data);
after
$obj->{'category_id'} , $obj->{'username'} , $obj->{'password'}
May be this help you !
It seems that you didn't json_decode() the JSON string, or $res is not the result of json_decode().
Example:
$json = '{
"_total": 1,
"values": [{
"id": 123456,
"name": "Example Technologies "
}]
}';
$res = json_decode($json);
echo $res->_total;
you will need to run the string through json_decode first http://uk3.php.net/json_decode
which will return an array.
Here is Your String,
$data = '{ "_total": 1, "values": [{ "id": 123456, "name": "Example Technologies " }] }';
$test = (array)json_decode($data);
echo '<pre>';
print_r(objectToArray($test));
die;
Function is here
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
May be its help you!!

returning index from JSON returned array

Hi guys I was wonder how you can return the index based on ID with the following.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
for example, I want to get print the name based on ID. I've had a go at using array_search but it didn't like the structure of the array. I will be using it inside a sql loop and passing the ID from the query to return the name string from the array.
print $obj->{'data'}[0]->{'name'};
//where 0 is returned index based on a defined ID.
thanks a lot
The json_decode makes your variables into objects. To do a search, you could use:
// The extra true at the end makes it decode to associative arrays
$json = json_decode($friends, true);
findByName($json, 1234);
function findNameById($obj, $id) {
foreach($obj as $o) {
if($o['id'] == $id) return $o['name'];
}
return false;
}
You will need PHP 5.3 in order to utilize the following closure and enhanced ternary operator (prints name if record is found; otherwise, prints 'No record found.'):
$findById = function($id) use ($friends) {
foreach (json_decode($friends)->data as $friend) {
if ($friend->id === $id) return $friend->name;
}
return;
};
echo $findById('125930') ?: 'No record found.';
Nice thing about this is that you can pass this callable around and it will remember the scope it was defined with. This means that you can pass any ID but the $friends array will always be available to the closure.

Categories