I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="[email protected]"
$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": "[email protected]",
"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?
Kara
6,23616 gold badges54 silver badges58 bronze badges
asked Mar 23, 2016 at 1:31
user914425
16.5k5 gold badges34 silver badges41 bronze badges
3 Answers 3
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
answered Mar 23, 2016 at 1:41
JSelser
3,6601 gold badge23 silver badges42 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Mar 23, 2016 at 1:41
Phil
166k25 gold badges265 silver badges269 bronze badges
1 Comment
user914425
thank you! I will pass $properties to json_encode()
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()
)
);
answered Mar 23, 2016 at 1:41
Matthew Herbst
32.3k27 gold badges92 silver badges141 bronze badges
Comments
lang-php
json_encodewill encode any variable to JSON, regardless of how nested it is.