Add new data into PHP JSON string

谁说我不能喝 提交于 2019-12-17 19:38:44

问题


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 ?


回答1:


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




回答2:


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




回答3:


$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);


来源:https://stackoverflow.com/questions/1745052/add-new-data-into-php-json-string

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