Convert PHP to JSON with Nested Array - php

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

Related

How to get a object value nested inside document in a collection in MongoDB PHP

I have stored a document set in MongoDB like below where ID is generated automatically through PHP
{
"_id": {
"$oid": "5ff745237d1b0000860007a6"
},
"user": "5ff741fb7d1b0000860007a4",
"name": "Test",
"slug": "fed73b70d080584c21e0a4353825ef91",
"category": "5fef4a467d1b000086000745",
"images": [{
"100x128": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"200x256": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"300x385": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"500x642": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg"
},
{
"100x128": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"200x256": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"300x385": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg",
"500x642": "test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg"
}],
}
Now the problem is I want to get value from images object from key 100x128 only from the first array.
I am using the below code to achieve
$productsArray = $collection->aggregate(
[
[
'$match' => [
'user_id' => $user_id
]
],
[ '$unwind' => '$images' ],
[ '$unwind' => '$images.100x128' ],
[
'$project' => [
'name' => 1,
'image' => '$images'
]
]
]
);
and I always get an output as below
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 5ff745357d1b0000860007a7
)
[name] => Test 1
[image] => MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[100x128] => test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg
[200x256] => test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg
[300x385] => test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg
[500x642] => test/year/month/image_da4181762396a31ff44f5ddc08ce6186.jpeg
)
)
)
)
I am not sure how to get just that specific value. Where am i going wrong here?
As far as i am getting your question it looks like you would need to understand the mongo concept. So you might get an array representation in UI or in PHP but at the end of day it is object.
Look closely the format that you have posted there is no array but multiple {} in that object just like JS so forget about array concept here.
If my understanding is correct this is what you are looking for
$productsArray = $collection->aggregate(
[
[
'$match' => [
'user_id' => $user_id
]
],
[ '$unwind' => '$images' ],
[ '$unwind' => '$images.100x128' ],
[
'$project' => [
'name' => 1,
'image' => '$images.100x128'
]
]
]
);
Whatever you have googled or used it is correct just you need to add the second unwind value i.e $images.100x128 instead of $images in the $project variable.
You can understand this way that $unwind variable uses recursive logic to get output as you want. Like let's say you have an array inside an array first it will get values from internal array then it will come to parent array and then so on. So the last value in $unwind variable should be used.
I am not sure if it will work on multiple objects but as you said you just need the first one. This should do the charm.

json_encode treats a single element array as object [duplicate]

This question already has answers here:
How to add square braces around subarray data inside of a json encoded string?
(3 answers)
Closed 6 months ago.
this is the json i have to produce
{
"email": "example#example.com",
"campaign": {
"campaignId": "p86zQ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if i use
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
];
and i do json_encode($data)
value is an object, but it should be an array with a single element. Somehow json_encode treats it as an object. Can i force it to treat it as an array with a single element ?
Thanks in Advance
Adrian
At the moment, you have a single array with 2 elements, instead of an array with a single element of a sub-array. In order to get the json in the first section, you need to add another array level.
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
[
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
]
];
That will give you this:
{
"email": null,
"campaign": {
"campaignId": "4JIXJ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if there is one single element in the array the json_encode will treat is as an object and the key of the object is the index of the array
to treat it as an array you can use array_values(<your_array>)

Remove quotation marks from php number

I know this has been asked before, however nothing seems to work
I have following json output:
"coordinates": [
"18.366466",
"29.898110"
]
However, the output I want is:
"coordinates": [
18.366466,
29.898110
]
$coordinates = array($result->lat, $result->lng);
$output[$i++] = array(
"type" => "Feature",
"geometry" => array("type" => "Point",
"coordinates" => $coordinates),
"properties" => array(
"ID" => $result->id,
"icon" => $result->icon,
"tags" => $tagsForJson,
"title" => $result->title,
"description" => $result->description));
Trim, str_replace and all of those functions are not working
Thank you!
What you're looking to do is type-cast this data into an float.
After preparing (trimming, etc) the string with the numbers, you can do something like this:
$coordinates = array((float)$result->lat, (float)$result->lng);
Or to cast the whole array at once, more simply you could utilize array_map and floatval
$coordinates = array_map('floatval', $coordinates);

PHP - How to create JSON with JSON object inside [duplicate]

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

PHP & JSON: Inserting an array in a nested array

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

Categories