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! :|
Related
I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);
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
);
I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format
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 am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);