将新数据添加到 PHP JSON 字符串中
我有 $data 作为 JSON 编码数据,并且有这个字符串:
$new_data = "color:'red'";
需要将其添加到 $data 中,以便我可以将其作为 json 字符串读取。
我怎样才能做到这一点?
I have $data as JSON encoded data and I have this string:
$new_data = "color:'red'";
that needs to be added to $data so that I can read it from it as a json string.
How can I achieve this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只是在寻找这个问题的解决方案,并偶然发现了这个问题(已经一岁了)。到目前为止提供的答案对我来说没有多大帮助。所以,希望这对下一个人有帮助。
我正在寻找的答案是以
数组结构而不是对象返回结果。然后,添加新值非常简单:
之后,当然可以使用 json_encode() 将数据返回到字符串中。
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
which returns the result in an array structure, not an object. Then, it is quite simple to add new values:
After this, the data can of course be returned into a string with
json_encode()
.您需要先
json_decode($data)
,然后添加新的键/值,然后json_encode()
它。you need to
json_decode($data)
first, then add the new key/value, andjson_encode()
it.