看起来您正在尝试向根 JSON 对象添加新元素,在这种情况下,您只需:
- 将 JSON 对象解码为 PHP 数组。
- 将数组合并为一个。
- 将合并后的数组编码回 JSON。
$field1 = '{"field_name":{"type":"text", "visual_name":"Field Name", "required":true}}';
$field2 = '{"field_name2":{"type":"select", "visual_name":"Field Name 2", "required":true, "options":{"opt1":"yes", "opt2":"no"}}}';
$arr = array_merge(json_decode($json1, true), json_decode($json2, true));
$json = json_encode($arr);
最终的$json 对象将是:
{
"field_name": {
"type": "text",
"visual_name": "Field Name",
"required": true
},
"field_name2": {
"type": "select",
"visual_name": "Field Name 2",
"required": true,
"options": {
"opt1": "yes",
"opt2": "no"
}
}
}
如果您想将字段添加到 JSON 数组而不是对象中,您可以这样做:
$arr = [json_decode($json1, true), json_decode($json2, true)];
结果:
[
{
"field_name": {
"type": "text",
"visual_name": "Field Name",
"required": true
}
},
{
"field_name2": {
"type": "select",
"visual_name": "Field Name 2",
"required": true,
"options": {
"opt1": "yes",
"opt2": "no"
}
}
}
]
注意
如果您尝试添加您在问题中给出的原始第二个字段,它将不起作用,因为它不是完全格式化的 JSON 字符串。您必须确保它有一对外花括号。
不正确:
"field_name2":{"type":"select", "visual_name": ...}
正确:
{"field_name2":{"type":"select", "visual_name": ...}}