Add new data into PHP JSON string

拜拜、爱过 提交于 2019-11-28 11:11:53

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

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

$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!