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


Building a JSON string with multiple level arrays in PHP

我需要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需要是一个数组,所以在末尾添加了额外的[],而primaryFieldscoupon对象的属性

分析错误:语法错误,意外的"["