I am trying to create mongoDB subdocuments record inside PHP code,
{
"_id": "",
"ref": [
{
"crm_base_contact_id": "1653",
"crm_imported_files_id": "906"
}
],
"data": [
{
"First_name": "Annalee",
"Last_name": "Graleski",
},
{
"First_name": "Henry",
"Last_name": "Smith",
}
],
}
How to create two arrays inside "data" subdocuments in php code .
Please provide me any idea to insert this in mongoDB using PHP code,
You can add additional fields with the $set operator when updating a document:
db.collection.update({},{"$set": { "history": "value" }})
If you want that field to be an array or sub-document then it is just the same:
db.collection.update({},{"$set": { "history": ["a","b","c"] }})
If you are struggling with converting the JSON syntax into php code, then here is something that will help you in the future:
$result = '{"$set": { "history": ["a","b","c"] }}';
echo var_dump( json_decode( $result ) );
$test = array( '$set' => array('history' => array( 'a', 'b', 'c') ) );
echo json_encode( $test ) ."\n"
So the first line just decodes the json and will dump what it should look like. If you are not sure, then json_encode your php array declaration to see that you have it right.
Related
I'm getting via url querystring variables like:
myserver_state=1&myserver_running=2&myserver_mem=3
Currently i'm adding to an existing json like:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver_state": "1",
"myserver_running": "2",
"myserver_mem": "3"
}
And i really want it like this:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
I'm using this to load them:
$formdata = array(
'state'=> $_POST['state'],
'uassip'=> $_POST['uassip'],
'uassipport'=> $_POST['uassipport'],
'c_uacminrtpport'=> $_POST['c_uacminrtpport'],
'c_uacmaxrtpport'=> $_POST['c_uacmaxrtpport'],
'c_cps'=> $_POST['c_cps'],
'c_totalcalls'=> $_POST['c_totalcalls'],
'c_maxchannels'=> $_POST['c_maxchannels'],
'c_duration'=> $_POST['c_duration'],
'c_to'=> $_POST['c_to'],
'c_uacxml'=> $_POST['c_uacxml']
);
echo "fromdata: <br>"; echo var_dump($formdata) . "<br><hr>";
if(file_put_contents('testconfig.json', json_encode($formdata) )) echo 'OK';
else echo 'Unable to save data in "testconfig.json"';
Many thanks!
EDIT:
following comments i tried:
status.php?server1[current_state]=10
this actually works to:
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_state": "10"
}
}
Which is great, BUT, if i then want to add an element like this:
status.php?server1[current_mem]=1
This actually REPLACES the whole server1
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_mem": "10"
}
}
and i lose the already existing current_state
Just use multidimensional array within your URL like:
test.php?key1=1&key2=2&myserver[state]=1&myserver[running]=2&myserver[mem]=3
so easy script
<?php
echo '<pre>';
echo json_encode($_GET, JSON_PRETTY_PRINT);
will give you
{
"key1": "1",
"key2": "2",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
of course, if required you can use also POST request with the same naming rules.
in order to create a nested JSON object, you need to create an array within an array.
E.g.
$example = [
'key1' => 'foo',
'key2' => 'bar',
'key3' => [
'subkey1' => 'foo',
'subkey2' => 'bar',
],
];
When running it through json_encode(), it will result in
{
"key1": "foo",
"key2": "bar",
"key3": {
"subkey1": "foo",
"subkey2": "bar"
}
}
Also it's not necessary to load form data like this –
$formdata = [
'state' => $_POST['state'],
'uassip' => $_POST['uassip'],
'uassipport' => $_POST['uassipport'],
'c_uacminrtpport' => $_POST['c_uacminrtpport'],
'c_uacmaxrtpport' => $_POST['c_uacmaxrtpport'],
'c_cps' => $_POST['c_cps'],
'c_totalcalls' => $_POST['c_totalcalls'],
'c_maxchannels' => $_POST['c_maxchannels'],
'c_duration' => $_POST['c_duration'],
'c_to' => $_POST['c_to'],
'c_uacxml' => $_POST['c_uacxml'],
];
Since the $_POST already contains a structure that you are trying to recreate. You can simply assign the post data to a new varaible.
On another note, I highly recommend you to check out PSR PHP standards, they will greatly help to improve code readability and your code structure :) https://www.php-fig.org/psr/
I've been trying to do this for a while now and I just can't seem to get it right. One post got me very close but not quite there because my of JSON's hierarchy. (it's an assignment and this hierarchy is mandatory.)
What I do right now is submit info from one page, POST it to my php on another page, save it in an array there, json_encode that array and write that to my JSON file.
Here is my watered-down code, hopefully getting rid of most unnecessary code:
<?php
$filename = "json/exercises.json";
$filesize = filesize($filename);
$fp = fopen($filename, "r+");
#Accept the submitted form
$exLanguage = $_POST['exLanguage'];
$exTitle = $_POST['exTitle'];
$exStuff = $_POST['exStuff'];
#write to JSON with an incrementing ID
if (file_get_contents($filename) == "") {
$exercise = array (
"id" => 1,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
} else {
#Get the last set ID
$jsonid = json_decode(fread($fp, $filesize), true);
$last = end($jsonid);
$title = prev($jsonid);
$lang = prev($jsonid);
$id = prev($jsonid);
$exercise = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
}
?>
now what this does is if my json is empty it adds the first array correctly with the ID at 1. Then if I try to add to my json again it adds it correctly with the ID at 2. But any more attempted writes to the JSON will give me these errors:
Warning: end() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
I tried doing a
$reset = reset($jsonid);
after writing to file but that didn't work, just gave me another error on the 3rd write for the reset being given a null too.
Can anyone please tell me how to get this too work? Or if there is a much easier way of getting this done?
Understand JSON format first. Its a collection of Objects which means attribute: value pair wrapped in {} and separated by comma , and then again wrapped in {} OR [] at top level.
Your JSON structure is incomplete or corrupted. What you are doing currently will create JSON in following format in your JSON file:
{ "id": 1, "lang": "as", "title": "asdsad" }
{ "id": 2, "lang": "as", "title": "asdsad" }
{ "id": 3, "lang": "as", "title": "asdsad" }
{ "id": 4, "lang": "as", "title": "asdsad" }
So json_decode will return null in this case because of invalid JSON format.
You need to keep appending your new JSON in existing JSON such that above format will become like this:
[
{ "id": 1, "lang": "as", "title": "asdsad" },
{ "id": 2, "lang": "as", "title": "asdsad" },
{ "id": 3, "lang": "as", "title": "asdsad" },
{ "id": 4, "lang": "as", "title": "asdsad" }
]
Which means your else block is incorrect. Use following code in else block:
$jsonid = json_decode(file_get_contents($filename), true);
$last = end($jsonid);
$id = $last['id'];
$jsonid[] = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" => array("exStuff" => $exStuff)
);
$exercise_json = json_encode($jsonid, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
I hope you are not bound to use that incorrect/corrupted JSON format. That will not work with json_decode() in any case.
i am using Codeigniter and inside a function i call a controller to return data which I want to use in an foreach to built an insert statement.
The JSON returned looks like this:
{
"Data": [
{
"id": "743",
"day": "1",
"day_type": "Party",
"day_dresscode": "Black",
"day_p_id": "1",
"description": "Test desc",
"name": "test"
},
{
"id": "743",
"day": "2",
"day_type": "Party",
"day_dresscode": "White",
"day_p_id": "1",
"description": "Test desc 1",
"name": "test 2"
}
]
}
my php looks like below:
// This where i got my JSON
$datavar = $this->model->get_json_data($id,$code);
// This is to decode the JSON
$datavar_decode['Data'] = json_decode($datavar,true);
Below is my foreach:
$i = 1;
foreach($datavar_decode['Data'] as $data):
$data_insert = array(
'val1' => $data['val1'],
'val2' => $data['val2'],
'val3' => $data['val3'],
'val4' => $data['val4']
);
$this->db->insert('mssqltable', $data_insert);
$i++;
endforeach;
It gives me below error:
Invalid argument supplied for foreach()
Don't use json.
You're problem is that you are returning an array of objects, and that's the behavior you get from $query->result() or if you use $query->row() then you get an object representing a single row.
In order to return an array, use $query->row_array() for a single row, or for multiple records returned you would use $query->result_array().
See all the details: https://www.codeigniter.com/user_guide/database/results.html
You can try this code to test that your $datavar_decode['Data'] doesn't allocate an empty array when you've got nothing to begin with anyway.
if (is_array($datavar_decode['Data']) || is_object($datavar_decode['Data']))
{
foreach ($datavar_decode['Data'] as $data)
{
...
}
}
I don't work with php much and I'm a little fuzzy on object creation. I need to make a webservice request sending json and I think I have that part covered. Before I can submit the data I need to create a nested object. I was assuming this would be trivial based on my experience with ecma based scripting languages, but I'm finding the syntax to be difficult to navigate. The object I want to create is below.
{ "client": {
"build": "1.0",
"name": "xxxxxx",
"version": "1.0"
},
"protocolVersion": 4,
"data": {
"distributorId": "xxxx",
"distributorPin": "xxxx",
"locale": "en-US"
}
}
I've seen a lot of examples of flat objects, but I haven't found a minimal example for a nested object yet. What would be the php syntax for the object above? Is this an unusual thing to do in php?
this JSON structure can be created by following PHP code
$json = json_encode(array(
"client" => array(
"build" => "1.0",
"name" => "xxxxxx",
"version" => "1.0"
),
"protocolVersion" => 4,
"data" => array(
"distributorId" => "xxxx",
"distributorPin" => "xxxx",
"locale" => "en-US"
)
));
see json_encode
Hey here is a quick trick to manually convert complex JSONs into a PHP Object.
Grab the JSON example as you have:
{ "client": {
"build": "1.0",
"name": "xxxxxx",
"version": "1.0"
},
"protocolVersion": 4,
"data": {
"distributorId": "xxxx",
"distributorPin": "xxxx",
"locale": "en-US"
}
}
Search-Replace { to array(
Search-Replace : to =>
Search-Replace } to )
Done.
User array to get the correct format and then call echo json_encode(array)
array( "client" => array(
"build" => "1.0",
"name" => "xxxxxx",
"version" => "1.0"
),
"protocolVersion" => 4,
"data" => array(
"distributorId" => "xxxx",
"distributorPin" => "xxxx",
"locale" => "en-US"
))
$client = new Client();
$client->information = new Information();
$client->information->build = '1.0';
$client->information->name = 'xxxxxx';
$client->information->version = '1.0';
$client->protocolVersion = 4;
$client->data = new Data();
$client->data->distributorId = "xxxx";
$client->data->distributorPin = "xxxx";
$client->data->locale = "en-US";
Perhaps something like the above? The client would hold two objects. Information and Data.
Edit
Using json_encode, you would create this object as an array in PHP..
$clientObj = array('client'=>
array( array('build'=>'1.0','name'=>'xxxx', 'version'=>'1.0'),
'protocolVersion'=>4,
'data'=>array('distributorId' => 'xxxx', 'distributorPin' => 'xxxx', 'locale' => 'en-US')
);
print json_encode($clientObj);
We can also construct nested array and then do a json_encode to construct nested JSON.
For e.g:
{"User":
{"username":"test",
"address":"Posted value fro address field",
"location":{
"id":12345
}
}
}
Above output we can achieve by writing below php code:
<?php
$obj = array(
'username'=>$lv_username,
'address'=>$lv_address,
'location'=>array('id'=>$lv_locationId)
);
$data = '{"User":'. json_encode($obj) .'}';
echo $data;
?>
Hope it helps.
Use the in build function of PHP:
json_encode();
this will convert the array into JSON object.
You can use json_encode to encode a php array
http://php.net/manual/en/function.json-encode.php
$theArray = array('client'= array('build'=>'1.0',
'name'=>'xxxxx',
'version'=>'1.0'
),
'protocolVersion'=> 4,
'data'=> array('distributorId'=>'xxxx',
'distributorPin'=>'xxxx',
'locale'=>'en-US'
)
);
$theObj = json_encode($theArray);
hopefully this helps..
posted it, then seen loads of answers already! :|
I'm trying to recreate json from a DB, for the client side. Unfortunately some of the keys in the json are numbers, which work fine in javascript, however as a result PHP keeps treating them as numeric instead of associative arrays. each key is for a document. let me show you:
PHP:
$jsonobj;
while ($row = mysql_fetch_assoc($ms)) {
$key = strval($row["localcardid"]);
$jsonobj[$key] = json_decode($row["json"]);
}
// $jsonobj ist still a numeric array
echo json_encode($jsonobj);
the resulting json should look like this:
{
"0": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
"1": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
}
One obvious solution would be to save the whole json without splitting in up. however that doesnt seem wise in regards to the db. i wanna be able to access each document seperately. using
$jsonobj = array ($key => json_decode($row["json"]));
obviously works, but unfortunately just for one key...
EDIT: for clarification*
in php: there's a difference between
array("a", "b", "c")
and
array ("1" => "a", "2" => "b", "3" => "c").
the latter, when done like this $array["1"] = "a" results in array("a") instead of array("1" => "a")
ANSWERED HERE
Try
echo json_encode((object)$jsonobj);
I believe if you pass the JSON_FORCE_OBJECT option, it should output the object with numeric indexes like you want:
$obj = json_encode($jsonObj, JSON_FORCE_OBJECT);
Example:
$array = array();
$array[0] = array('test' => 'yes', 'div' => 'first', 'span' => 'no');
$array[1] = array('test' => 'no', 'div' => 'second', 'span' => 'no');
$array[2] = array('test' => 'maybe', 'div' => 'third', 'span' => 'yes');
$obj = json_encode($array, JSON_FORCE_OBJECT);
echo $obj;
Output:
{
"0": {
"test": "yes",
"div": "first",
"span": "no"
},
"1": {
"test": "no",
"div": "second",
"span": "no"
},
"2": {
"test": "maybe",
"div": "third",
"span": "yes"
}
}
Simply save both inside a single entry in the database: the separate field values AND the whole json structure inside a separate column. This way you can search by single fields and still get the valid json structure for easy handling.
For setting a number as key in associative array we can use following code
$arr=array(); //declare array variable
$arr[121]='Item1';//assign Value
$arr[457]='Item2';
.
.
.
print_r($arr);//print value