user914425
user914425

Reputation: 16483

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="[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?

Upvotes: 0

Views: 677

Answers (3)

JSelser
JSelser

Reputation: 3630

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

Upvotes: 1

Matthew Herbst
Matthew Herbst

Reputation: 31973

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

Upvotes: 0

Phil
Phil

Reputation: 164736

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.

Upvotes: 1

Related Questions