I want use zachhunters json to html tabel script with my postressql db so i need a specific JSON string format but i dont know how to build it ... (i am new in json)
Link to the Script
I get my data using
$result = pg_fetch_array($rs, NULL, PGSQL_ASSOC);
When i use json_encode($result) i get this:
{"id":"2","surname":"Max","name":"Muster"} etc.
For the Script i need somthing like:
{ "d": "[{\"id\":1,\"Username\":\"Sam Smith\"},{\"id\":2,\"UserName\":\"Fred Frankly\"}]" }
How can i handle this?
In each loop where you fetch an element from your database store the $result in an array $rows.
After the loop simply use json_encode(array('d' => $rows)) to create JSON containing all your data.
Related
I wrote a function wheere I need to store some data in database.
I have multidimensional associative array.
I dumped one part of the code..
When I dump:
$csv->setCode($data[7]);
dump($data[7]);die;
and I get
"{"id":"131-2-0-615317","o":"raccoon-events-ltd","j":"Member of the...","c":"Sport For All..."}"
Now, I need to pull out just the "ID" part of the code..
I just tried:
dump($data[7]=>id);die;
Its JSON
use this code:
$json = json_decode($data[7],true);
dump($json['id']);die;
I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>
IP.Nexus puts custom fields into a table all muddled up into one row and some how pulls the correct data out.
basically my custom fields row looks like so:
a:2:{i:2;s:4:"Test";i:3;s:10:"Accounting";}
How do i select what item to pull as i would like to out put just one item not the whole row, is it with delimiters or string splitter, as i am novice with this part of mySQL
Cause i would like to echo out just the advertising on its own and also vice versa for the testing.
Thanks in advance
It's a serialized array using serialize() function so you can get its contents using unserialize($YourString);.
But I see that you string is corrupted for deserialization, because s:4: in s:4:"advertising" says that after s:4: 4 character long string is expected that advertising is not.
The data in the database is in serialized(json) form.You can turn it into simple array using unserialize.
For example;if $mystr is your string
write
$mystring=unserialize($mystring)
You will get normal array of this string
You can do
foreach($mystring as $str){
$ads[]=$str['advertising'];
}
and the resulting array $ads will be the ads you like in simple array form
Since this looks as JSon, you can use a PHP JSon module to parse each row from MySQL.
<?php
(...)
while (...) {
$obj = json_decode($row);
// do something with $obj
}
I have an Android application which sends json data to PHP script.
The PHP script have to save the data into MongoDB.
When I insert the data, MongoDB treat this data as a string.
$conn = new Mongo('mongodb://127.0.0.1:27017');
// access database
$db = $conn->Data;
// access collection
$collection = $db->Collection;
$collection->insert($myjson)
How can I say to MongoDB PHP driver that it is already a json document?
Thanks
The PHP MongDB Driver accepts arrays for inserts and queries (see here: http://www.php.net/manual/en/mongo.queries.php)
So you need to convert your JSON to an array.
Luckily, in general this is quite easy ... here is a snippet from a longer piece of code (see this article) to insert JSON data from the Twitter API into an array, then into MongoDB:
// Convert JSON to a PHP array
$usertimeline = json_decode($usertimeline);
// Loop array and create seperate documents for each tweet
foreach ($usertimeline as $id => $item) {
$collection->insert($item);
}
Note the json_decode() function can convert to an array by passing true as the second parameter.
Here's a tip for others who want to do this, but want to update records rather than insert new ones. In order to get Justin's approach to work, I had to make sure that I convert the _id object for each item to a MongoId:
// Convert JSON to a PHP array
$usertimeline = json_decode($usertimeline);
// Loop array and create seperate documents for each tweet
foreach ($usertimeline as $id => $item) {
$mongo_id = new MongoId($id);
$item->_id = $mongo_id;
$collection->update(array('_id' => $mongo_id), $item);
}
MongoDB uses BSON not JSON so you need to re-encode anyways. Also, I remember talking to kchodorow about this and the raw interface was not exposed then (been half a year at least) and I doubt it is now so even if you manage to get BSON data from somewhere , you can't avoid the de/encode.
As MongoDB PHP library supports conversion from JSON to BSON and BSON to PHP Std Class Object, You can follow simple steps.
//Convert Row (Document) to json
$json_row = json_encode($row);
//Convert JSON to BSON
$bson = \MongoDB\BSON\fromJSON($json_row);
//Convert BSON to PHP Std Class object
$row = \MongoDB\BSON\toPHP($bson);
// Insert Record to Document
$collection->insertOne($row);
You can get full MongoDB database backup and restore script from here
https://github.com/sulochanatutorials/php-mongodb-backup-restore
UPDATE 2021 WITH PHP 7 DRIVER:
Lets say your json string is
$myjson = {"name":"foo", "age":30}
First decode it with PHP json_decode. Which returns an array.
$myarraydata = json_decode($myjson)
Now you can directly insert it into mongoDB
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert($myarraydata);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $connection->executeBulkWrite('dbname.collection_name', $bulk, $writeConcern);
Check bulk operation official documentation here.
I am reading one document requests processed trough another document using AJAX.
In document processed trough AJAX i want to generate JSON array because its only way i can pass two variables and then spread them like this
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0])));
now i generating code like this
$results2 = mysql_query('SELECT full, short FROM `Countries` WHERE '.$cities);
$json = array();
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = $result2['short'].','.$result2['full'];
}
json_encode manual is pretty clear about its usage, check 'Example #2 A json_encode() example showing all the options in action' in http://ar.php.net/manual/en/function.json-encode.php
json_encode converts standard php arrays to JSON.
Anyway, your SQL code is not correct. You must use mysql_fetch_array for getting the values from results2, and 'short' and 'full' are not in your query.