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/
Related
This question already has answers here:
create nested JSON object in php?
(7 answers)
Closed last year.
I have to comunicate with some API which expect JSON.
Until now I was fine because I needed just simple json so I just create array like this:
$data = array (
"firstName" => "TEXT1",
"lastName" => "TEXT2",
"license" => "TEXT3",
"password" => "TEXT4",
"username" => "TEXT5"
);
And after that just simple
$data_string = json_encode($data);
So final JSON looks like:
{
"firstName": "TEXT1",
"lastName": "TEXT2",
"license": "TEXT3",
"password": "TEXT4",
"username": "TEXT5"
}
However now I have to change it a bit and I am confuse, my new JSON shoud looks like:
{
"contact": {
"city": "New Yourk",
"email": "my#mail.com",
"phone": "777888999",
"postCode": "07101",
"street": "Street N. 12"
},
"enabled": true,
"firstName": "Robert",
"lastName": "Exer",
"username": "login#login.com",
"license": "text",
"password": "text"
}
As you can see it is basicly just added contact part. I was thinking how I can do this but only think I found was something like to insert array to existing $data array and then json_encode this but this will not give me a contract: at start.
Of course there is possible to do it some other way like create one json and then another and hardly connect string and so on. But i believe there have to be some better way how to do things like this.
I apprciate any advise:)
Just put an array in the value of contact:
$data = array(
'contact' => array(
'city' => 'New York',
'email' => 'my#mail.com',
//...
),
'enabled' => true,
'firstName' => 'Robert',
'lastName' => 'Exer',
//...
);
$data_string = json_encode($data);
An array can contain another array, which will be encoded as a separate object inside the previous object:
$data = array (
"contact" => array(
"city" => "New Yourk",
"email" => "my#mail.com",
"phone" => "777888999",
"postCode" => "07101",
"street" => "Street N. 12"
),
"enabled": true,
.. etc
);
This is my first time using PHP and I am making a script that will output text in JSON format. However I am encountering problems with the formatting.
Can someone explain why my browser renders the following code as..
"1", 'b' => "2", ), array( 'a' => "1", 'b' => "2", 'c' => "3", ) ) ); ?>
instead of something like this?
[
[ { "a" : "1" }, { "b" : "2" } ],
[ { "a" : "1" }, { "b" : "2" }, { "c" : "3" } ]
]
Code:
<body>
<?php
echo json_encode(
array(
array(
'a' => "1",
'b' => "2"
),
array(
'a' => "1",
'b' => "2",
'c' => "3"
)
)
);
?>
</body>
Your code is correct, but the setup doesn't seem right. Your PHP code isn't evaluated. What happens if you put nothing but
<?php phpinfo(); ?>
into your file? Does it show only the code or a long table with all kinds of infos? If it's the former, then you need to find out how to get your webserver to interpret the embedded PHP code before sending it to your browser.
Save file as YourFile.php
Run on Xampp server like localhost/yourFile.php , not like D://File....bla bla
You saved your file as html.
Change your file from FileName.html to FileName.php
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.
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
I know how to decode a JSON string with one object with your help from this example How to decode a JSON String
But now I would like to improve decoding JSON string with several objects and I can't understand how to do it.
Here is an example:
{ "inbox": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"sent": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"draft": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
How to make just one foreach() to
decode above JSON string?
How to detect object's names: inbox,
sent or draft on this foreach()?
New answer
Re your revised question: foreach actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:
$data = json_decode($json);
foreach ($data as $name => $value) {
// This will loop three times:
// $name = inbox
// $name = sent
// $name = draft
// ...with $value as the value of that property
}
Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a "firstName" property, this code:
$data = json_decode($json);
foreach ($data as $name => $value) {
echo $name . ':'
foreach ($value as $entry) {
echo ' ' . $entry->firstName;
}
}
...will show:
inbox:
Brett
Jason
Elliotte
sent:
Issac
Tad
Frank
draft:
Eric
Sergei
Old answer(s)
Begin edit
Re your comment:
Now I would like to know how to decode JSON string with several objects!
The example you posted does have several objects, they're just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:
{"name": "I'm the first object"},
{"name": "I'm the second object"}
That JSON is not valid. There has to be a single top-level object. It might just contain an array:
{"objects": [
{"name": "I'm the first object"},
{"name": "I'm the second object"}
]}
...or of course you can give the individual objects names:
{
"obj0": {"name": "I'm the first object"},
"obj1": {"name": "I'm the second object"}
}
End edit
Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it's not much different from the example in the question you linked (which also has an object with properties that have array values).
So:
$data = json_decode($json);
foreach ($data->programmers as $programmer) {
// ...use $programmer for something...
}
foreach ($data->authors as $author) {
// ...use $author for something...
}
foreach ($data->musicians as $musician) {
// ...use $musician for something...
}
You can use the json_decode function to decode the JSON string :
$json = <<<JSON
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
JSON;
$data = json_decode($json);
Then, to see what the data looks like, you can dump it :
var_dump($data);
And you'll see you have an object containing three arrays, each one containing other sub-objects :
object(stdClass)[1]
public 'programmers' =>
array
0 =>
object(stdClass)[2]
public 'firstName' => string 'Brett' (length=5)
public 'lastName' => string 'McLaughlin' (length=10)
1 =>
object(stdClass)[3]
public 'firstName' => string 'Jason' (length=5)
public 'lastName' => string 'Hunter' (length=6)
...
public 'authors' =>
array
0 =>
object(stdClass)[5]
public 'firstName' => string 'Isaac' (length=5)
public 'lastName' => string 'Asimov' (length=6)
...
Which means you know how to access your data.
For example, to display the list of the programmers, you could use :
foreach ($data->programmers as $programmer) {
echo $programmer->firstName . ' ' . $programmer->lastName . '<br />';
}
Which would get you the following output :
Brett McLaughlin
Jason Hunter
Elliotte Harold