使用嵌套数组将PHP转换为JSON

时间:2016-03-23 01:31:51

标签: php arrays json

我有一个需要转换为JSON字符串的PHP变量。

我有以下PHP代码:

$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname@smsfree4all.com" 
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);

这很好用。但我不确定的是如何使用如下所示的嵌套键值对对PHP中的属性进行编码:

{
"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"
        }
    ]
   }
}

在键值之前@的含义是什么?

3 个答案:

答案 0 :(得分:1)

或许这样的事情?

$properties = [
    'property' => [
        ['@key' => 'console.rows_per_page', '@value' => 'user-summary=8'],
        ['@key' => 'console.order', '@value' => 'session-summary=1']
    ]
];

很难说出你在问什么。

答案 1 :(得分:1)

这样的事情应该这样做

$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

请注意:

  • key~value数组被编码到对象中
  • 常规数组(此处数组数组)编码为数组

这些是编码任意对象时需要考虑的所有规则

答案 2 :(得分:0)

您可以使用简单数组嵌套在PHP中,与JavaScript对象非常相似:

$grandparent = array(
  "person1" => array(
    "name" => "Jeff",
    "children" => array(
      array("name" => "Matt"),
      array("name" => "Bob")
    )
  ), 
  "person2" => array(
    "name" => "Dillan",
    "children" => array()
  )
);