【问题标题】:Add new data into PHP JSON string将新数据添加到 PHP JSON 字符串中
【发布时间】:2009-11-16 21:44:13
【问题描述】:

我有 $data 作为 JSON 编码数据,我有这个字符串:

$new_data = "color:'red'";

需要将其添加到 $data 以便我可以将其作为 json 字符串读取。

我怎样才能做到这一点?

【问题讨论】:

    标签: php json add new-operator


    【解决方案1】:

    我只是在寻找解决方案,偶然发现了这个问题(已经一岁了)。到目前为止提供的答案对我没有太大帮助。所以,希望这可以帮助下一个人。

    我一直在寻找的答案是

    $json = json_decode($data,true);
    

    它以数组结构而不是对象的形式返回结果。然后,添加新值就很简单了:

    $json['foo'] = 'bar';
    

    在这之后,数据当然可以返回成带有json_encode()的字符串。

    【讨论】:

      【解决方案2】:

      你需要先json_decode($data),然后添加新的键/值,然后json_encode()它。

      【讨论】:

        【解决方案3】:
        $dataToAugment = json_decode($data);
        
        // add you data here at the proper position
        
        $data = json_encode($dataToAugment);
        

        【讨论】:

          猜你喜欢
          • 2011-04-03
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-21
          • 2020-09-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多