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

发布于 2024-08-11 12:20:00 字数 157 浏览 5 评论 0原文

我有 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撩人痒 2024-08-18 12:20:00

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

我正在寻找的答案是以

$json = json_decode($data,true);

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

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

之后,当然可以使用 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

$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().

野却迷人 2024-08-18 12:20:00

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

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

海的爱人是光 2024-08-18 12:20:00
$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);
$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文