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