将新数据添加到 PHP JSON 字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1745052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:41:09  来源:igfitidea点击:

Add new data into PHP JSON string

phpjsonaddnew-operator

提问by Manny Calavera

I have $data as JSON encoded data and I have this string:

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

$new_data = "color:'red'";

that needs to be added to $data so that I can read it from it as a json string.

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

How can I achieve this ?

我怎样才能做到这一点?

回答by Ben

I was just searching for the solution to this and stumbled across this question (already one year old). The answers provided so far were not very helpful to me. So, hopefully this helps the next person.

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

The answer I was looking for was

我正在寻找的答案是

$json = json_decode($data,true);

which returns the result in an array structure, not an object. Then, it is quite simple to add new values:

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

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

After this, the data can of course be returned into a string with json_encode().

在此之后,数据当然可以返回到字符串中json_encode()

回答by cloudhead

you need to json_decode($data)first, then add the new key/value, and json_encode()it.

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

回答by Eineki

$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);