0

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?

3
  • 1
    Are you asking how to create the JSON shown in your question as a PHP object / array? Commented Mar 23, 2016 at 1:36
  • Where are you getting that JSON output from? PHP's json_encode will encode any variable to JSON, regardless of how nested it is. Commented Mar 23, 2016 at 1:36
  • @MatthewHerbst I am not sure how to specify the nested arrays (properties) in PHP to pass it into json_encode. Commented Mar 23, 2016 at 1:38

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

thank you! I will pass $properties to json_encode()
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.