The data is retrieved from the database then encoded into JSON data, then passed into the view:
$json_data = json_encode(array('questions' => $x));
$search_results['search_results'] = $json_data;
$this->load->view('findquestions',$search_results);
which looks like:
{"questions":[{"question_title":"java"},{"question_title":"big java book"}]}
How can the "question_title"s then be presented as separate links?
Does json_decode need to be used, then what
Related
I have a json file:
$json='[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
and my forms post data in variable
vars="fname"=>"Ameur","lname"=>"KHIL"
"fname"=>"Marak","lname"=>"Cristo"
and I like to insert in between my json content with variable to get the final json like this:
$result='[{"Email":"myemail1#domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2#domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.
Parsing the JSON-String
$json = json_decode('[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
Adding the new vars value and removing the additional ones. This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
And getting your result in a JSON-String
$result = json_encode($json);
In database JSON data is stored in below way:
{"name":"abc","score":5}
Now everytime I want to add json object with different name and score to same json data as :
{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}
Right now I have tried this code
$database_data = $row['JSONstring']; //fetched json string from database
$json_decode_data = json_decode($database);
array_push($json_decode_data, $new_json_string); //data to append to database data
$updated_json_data = json_encode($json_decode_data); // at last encode the update json data
But this don't work and throws a warning : Parameter 1 is an object.
How do solve it ?
Now with all the answer and comments given here I got the required answer. So I appreciate all your help.
In my question starting, the first JSON String format is invalid:
{"name":"abc","score":5}
Instead of this, it would be :
[{"name":"abc","score":5}]
Required JSON data's format would be:
[{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}]
And this is achieved by array_merge() function as follows:
Code to append json object to json object string
//fetched json string from database
ie.[{"name":"abc","score":5}]
$database_data = $row['JSONstring'];
//decode both string the database data string and the new one which is to be merged
$json_decode_database_data = json_decode($database_data, true);
$json_decode_new_data = json_decode($database_data, true);
//merge both the decoded array by array_merge()
$required_json_data = array_merge($json_decode_data, $new_json_string);
//at last encode required json data
$updated_json_data = json_encode($required_json_data);
// You will get required json data
[{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}]
I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code
public function json()
{
$content = $this->db->get('todolist'); //todolist table name
$data = $content->result_array();
echo json_encode($data);
}
Above code is converting database into JSON array.
Output
[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]
What will be best way to convert it into JSON object
Sangam try to understand the concept, check the following line:
$data = $content->result_array(); // $data is an array
echo json_encode($data); // here you are converting it into an json object
Your $data array contains more than one index in it that's why the json object is having multiple {} inside [];
You want to json_encode($data, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
Refer: PHP Array to Json Object
You can use JSON_FORCE_OBJECT see the example below.
echo json_encode($data, JSON_FORCE_OBJECT);
Assuming you're only getting one row back from your query.
change
echo json_encode($data);
to
echo json_encode($data[0]);
I am working on a project where a user has to fill up a form and can upload multiple documents. Everytime he uploads a document, he calls a webservice which returns a JSON file with id and type.
Since he can upload multiple documents so the webservice is called many times. When he completes his form and submits it, I need to send a json with the multiple id and type that I have received previously from JSON.
This is the JSON that I need to send to the server when the user finally submits the form:
"docls":[
{
"id":"123",
"ty":"101",
},
{
"id":"456",
"ty":"102",
}
],
How do I encode the JSON when I dont know how many files the user has uploaded?
P.S. I have already been able to get the response from the first JSON in the form of 'id' and 'ty'. Do I need to store it in array? If yes then how do I decode it into json?
$json_string = array(
'docls' => array (
'id' => '123',
'ty' => '101',
),
);
You're going to want to build the array with php then json_encode it when your ready to send it back to the server
// Create an array to hold the documents
$documents = [];
// push each document into the array as the user does their thing
$documents[$id] = $ty;
// When the user is finished
$json = json_encode($documents);
Well, you just have to use json_decode to convert json string you receive to php array, and json_encode to convert convert php array to json formatted string.
Check this example:
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
more information here
I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);