Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用多级数组构建JSON字符串_Php_Arrays_Json - Fatal编程技术网

在PHP中使用多级数组构建JSON字符串

在PHP中使用多级数组构建JSON字符串,php,arrays,json,Php,Arrays,Json,我需要PHP中的这个结果: $pass->setJSON('{ "formatVersion" : 1, "description" : "title", "coupon" : { "primaryFields" : [ { "key" : "offer", "label" : "title",

我需要PHP中的这个结果:

$pass->setJSON('{
          "formatVersion" : 1,
          "description" : "title",
          "coupon" : {
            "primaryFields" : [
              {
                "key" : "offer",
                "label" : "title",
                "value" : "50%"
              }
            ],
          }           
        }');
我尝试使用阵列构建此功能:

$jsonpost = array();
$jsonpost['formatVersion'] = '1';
$jsonpost['description'] = "test";
然后使用JSON_ENCODE进行转换:

$json = json_encode($jsonpost);
$pass->setJSON($json);
如何在PHP中设置多级数组(优惠券)?

您需要使用:

$jsonpost['coupon']['primaryFields'][] = [
'key' => 'offer',
'label' => 'title',
'value' => '50%',
];
或者,如果使用PHP<5.4,则应使用语法:

$jsonpost['coupon']['primaryFields'][] = array(
   'key' => 'offer',
   'label' => 'title',
   'value' => '50%',
);

这是因为Json中的
primaryFields
需要是一个数组,因此在末尾添加了额外的
[]
,而
primaryFields
优惠券
对象的属性

解析错误:语法错误,意外'['

没有解释,OP不知道他为什么要这样写!看看我编辑的答案,你可能使用PHP<5.4