【问题标题】:Add to a JSON object, with PHP使用 PHP 添加到 JSON 对象
【发布时间】:2021-01-02 10:55:42
【问题描述】:

我想用一个新的给定对象增加一个 JSON 对象,但我做不到。我有以下 JSON:

{ "field_name":{ "type":"text", "visual_name":"Field Name", "required": true } }

用户将创建更多字段,我想在原始 JSON 中插入这种格式的新字段:

"field_name2":{ "type":"select", "visual_name":"Field Name 2", "required": true, "options":{"opt1":"yes","opt2":"no"} }

【问题讨论】:

  • 这能回答你的问题吗? Merging two json in PHP
  • 谢谢,我会试试的
  • 我尝试了这段代码并且弄乱了我的 json 。将第二个 json 中的混乱选项合并为第三个

标签: php arrays json


【解决方案1】:

看起来您正在尝试向根 JSON 对象添加新元素,在这种情况下,您只需:

  1. 将 JSON 对象解码为 PHP 数组。
  2. 将数组合并为一个。
  3. 将合并后的数组编码回 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": ...}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2019-01-30
    • 1970-01-01
    • 2021-11-12
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多