简体   繁体   English

PHP json_encode-创建JSON数组

[英]PHP json_encode - create JSON array

I've used the json_encode function in the past to create simply JSON objects like this: 我过去曾使用json_encode函数来创建简单的JSON对象,如下所示:

$payload =  array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);

which creates this: 这创建了这个:

{"user":"john smith","password":"abc12345","group":"sales"}

I now need to generate a JSON array like this: 我现在需要生成这样的JSON数组:

{
  "query": [
    {
      "Date": "11/01/2017...12/31/2017"
    }
  ]
}

but I can't find the correct syntax. 但我找不到正确的语法。

You can simply create a 2d array in php. 您可以简单地在php中创建2d数组。

$payload =  array (
    "query" => array(
         array(
             "date" => "11/01/2017...12/31/2017",
             "other sub key" => "other sub value"
         )
    ),
    "other main key" => array(
         array(
             "other sub key" => "other sub value",
             etc...
         )
    )
);

That would be something like this 那会是这样的

$array = array(
    'query' => array(
        array('Date' => '11-01-2017')
        )
    );


echo '<pre>';
print_r(json_encode($array, JSON_PRETTY_PRINT));

Result 结果

{
    "query": [
        {
            "Date": "11-01-2017"
        }
    ]
}
$payload = json_encode($payload, JSON_PRETTY_PRINT);

参考: http : //php.net/manual/en/function.json-encode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM