How to build JSON array before posting to other document? - php

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.

Related

Decode json With PHP not working

I am trying to decode json with PHP but dont know where am i wrong. Here is my code
$rr ='var modelsGlobal = [{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}]';
$json = json_decode($rr, true);
foreach($json['modelsGlobal'] as $json){
$prod_id = $json["value"];
}
Please help
You are trying to decode (broken) JavaScript, not JSON.
JSON wouldn't include var modelsGlobal = and array members need a , between them.
Run your data through a linter.
After you fix the errors which are preventing the parsing, the JSON doesn't start with an object with a modelsGlobal, so loop over the array in $json directly.
Your JSON is incorrect. It is not JSON but JavaScript and it lacks a comma to separate the two objects of the array.
If you use PHP 5.3+ use json_last_error to check errors with json_encode/json_decode.

PHP build a specific JSON string from postgresql Database

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.

zend php multiple array json_encoding

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>

Sending an array of data to the server with jQuery

I am sending a CSV list to the server within the url. It is a list of songid's:
var $array = [];
oTable.find('td').each(function(){
$songdata = $(this).data('data');
$songid = $songdata.songid;
//The next line is the variable I need to also send along with each songid
$duration = $songdata.duration;
$array.push($songid)
});
This results in '24,25,32,48,87' being sent to the server.
I then use the following in my php script to convert it into an array:
$songs = $_GET['songid'];
$songarray = explode(",", $songs);
This works great, I can access the data properly and all is well.
However I now have the need to add another property to each of the songid's. As seen above, I need to add the $duration variable to the data sent and be able to convert it into an array server side. (or alternatively construct the actual array client side would be fine also)
How would I go about this?
You could use this to encode your array into JSON:
http://www.openjs.com/scripts/data/json_encode.php
And then send that String to your backend where you can unpack it with this:
$yourarray = json_decode($string)
I would create an object of the data in your jscript and send it over to the PHP and then use json_decode then you have an associative array of your data within the PHP
You always can use JSON for data serialization/deserealization as of Serializing to JSON in jQuery
try sending arrays to PHP in JSON format and then do json_decode($var) in your PHP script.
make an associative array server side
$array = new Array();
//add songid as key and duration as value
$array = array_push_assoc($array, $songid, $songduration);
echo json_encode($array);
on the client side after parsing the json
$.each(json,function(key,value){
//key will be the songid
//value will be the duration
});

Insert JSON into MongoDb directly from PHP

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.

Categories