Home > DeveloperSection > Forums > How to add attribute in JSON in PHP?
Kate Smith
Kate Smith

Total Post:24

Points:168
Posted on    June-20-2013 3:33 AM

 JSON JSON 
Ratings:


 1 Reply(s)
 1634  View(s)
Rate this:
Hi Developers,

I have Json in PHP like this:

$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';

and I want to add

"test1":"5","test2":"7"
into JSON above.

so it will be like this:

$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
    {"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]}';

Please, help me. How to add attribute in JSON in PHP?


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    June-20-2013 7:53 AM

Hi, 

Try as following 

$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';

// decode json
$json = json_decode($json);

// add data
$json->rows[0]->test1 = "5";
$json->rows[0]->test2 = "7";

// echo it for testing puproses
print_r($json);
// re-encode 
$json = json_encode($json);
echo $json;




Don't want to miss updates? Please click the below button!

Follow MindStick