Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new data into PHP JSON string

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 ?

like image 373
Manny Calavera Avatar asked Nov 16 '09 21:11

Manny Calavera


2 Answers

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

like image 184
Ben Avatar answered Oct 15 '22 23:10

Ben


$dataToAugment = json_decode($data);

// add you data here at the proper position

$data = json_encode($dataToAugment);
like image 29
Eineki Avatar answered Oct 16 '22 01:10

Eineki