JSON object in PHP with property - php

What would be the equivalent PHP array structure to create an object with identical properties:
For example... create the object 'columns' below in PHP using json_encode:
jQuery('#example').dataTable( {
"ajaxSource": "sources/objects.txt",
"columns": [
{ "data": "engine" },
{ "data": "browser" },
{ "data": "platform" },
{ "data": "version" },
{ "data": "grade" }
]
} );
(I am trying to build a dynamic datatable and define the columns in the source JSON.

You could use an ArrayObject
new ArrayObject([
"ajaxSource" => "...",
"columns" => [
new ArrayObject(['data' => 'engine']),
new ArrayObject(['data' => 'browser']),
new ArrayObject(['data' => 'etc'])
]
]);
if you want to assemble this you need to store the objects inside an array like
$columns = [];
for(...) {
$columns[] = new ArrayObject(['data' => 'etc']);
}
Have a look at http://php.net/manual/de/arrayobject.construct.php

Related

php convert multidimensional array to json object

PHP NEWBIE
[PHP 7.4]
I am trying to refactor some old code.
GOAL: The two JSON must match.
Code snipppet 1: Old JSON code generated from php array
Code snippet 2: New JSON code generated from php array
Objective: Both must match, I am using php unit to compare them. For simplicity, I have removed the testing code.
PROBLEM: Extra set of square brackets, see image below.
I tried Using JSON_FORCE_OBJECT, which removes the square brackets, but introduces {... john: { "0": { "byEmail" ... " and ... "marie": { "1" { "byEmail" ...
(Naming wise: I have used John and marie, but these could be promotions, offers, packages, etc. so ignore the naming please)
SNIPPET 1 - php code
$body = [
"data" => [
"john" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
],
"marie" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
]
]
];
This gets converted to this JSON object:
// SNIPPET 1 - running json_encode()
{
"data": {
"john": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
},
"marie": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
}
}
}
SNIPPET 2:
I am creating this data structure dynamically now, because future requirement may have johnByPost, johnByFax, etc.:
//my-file-dynamic-generation.php
public function constructArray($johnByEmail=null, $johnByPhone=null, $marieByEmail=null, $marieByPhone=null) {
$body = [ "data" => ["john" => [], "marie" => []]];
if ($johnByEmail !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byEmail", $johnByEmail));
}
if ($johnByPhone !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byPhoneCall", $johnByPhone));
}
if ($marieByEmail !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byEmail", $marieByEmail));
}
if ($marieByPhone !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byPhoneCall", $marieByPhone));
}
return $body;
}
// HELPER func
function createKeyValuePair($title=null, $status=null, $source="my-server") {
return [
$title => [
"status" => $status,
"source" => $source,
]
];
}
JSON - OUTPUT
I have tried to use json_encode($data, JSON_FORCE_OBJECT)
That resulted me to get an extra key, which I don't want (I got .... [0] => 'marie' => ... [1] => 'john'
Appreciate reading this, thanks!
You are creating a new array inside the function createKeyValuePair() (probably to add the key). You could use the function the create the content only, and create the key inside the function constructArray() :
$body["data"]["john"]["byEmail"] = $this->createKeyValuePair($johnByEmail);
and the function :
function createKeyValuePair($status = null, $source = "my-server"): array
{
return [
"status" => $status,
"source" => $source,
];
}

Add parent key to PHP JSON [duplicate]

This question already has an answer here:
php - converting from one json format to another
(1 answer)
Closed 1 year ago.
I've been trying to add a parent key "data" to a PHP $dataset json:
my $dataset json:
[
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
]
the final output must be
[
"data": {
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
},
]
Can you please help me? Thank you!
The easiest way is to decode to array and add the parent then encode again to json.
$output_json = json_encode(array("data" => json_decode($dataset)));
$data = [
'data' => $dataset,
'status' => true
];
return json_encode($data);
The syntax of JSON type is {key:vale}
your code should be like:
{
"data": [
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
],
}
Try this out:
$final_result = array('data' => $dataset)

Convert PHP to JSON with Nested Array

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()
)
);

Update MongoDB subdocument using PHP code

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.

How to decode a JSON String with several objects in PHP?

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

Categories