5

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?

5
  • You could parse the json string into an array using json_decode, add the new attributes to the array, and recreate the json string using json_encode. Commented Jun 19, 2013 at 16:19
  • possible duplicate of Add new data into PHP JSON string Commented Jun 19, 2013 at 16:23
  • the examples in stackoverflow.com/questions/1745052/… use array definitions. Rio is wanting to add attributes(properties) Commented Jun 19, 2013 at 16:30
  • @user20232359723568423357842364: You can simply pass true as second argument to json_decode. No difference. Apparently 4 years ago people didn't require so much hand-holding. Commented Jun 19, 2013 at 16:35
  • Beginners have always required hand-holding ;) 4 years ago there weren't as many around here Commented Jun 19, 2013 at 16:44

1 Answer 1

11
$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;
Sign up to request clarification or add additional context in comments.

8 Comments

{"total":"100","page":"1","records":"100","rows":[{"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}],"test1":"5","test2":"7"} its your final output.does not match to what is wanted
it should be like this: {"total":"100","page":"1","records":"100","rows":[{"no":"1","part_number":"2","p‌​art_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]} not like this: {"total":"100","page":"1","records":"100","rows":[{"no":"1","part_number":"2","p‌​art_name":"3","price":"4","note":"8"}],"test1":"5","test2‌​":"7"}
yeah sharif that's the output but not match to what is wanted, can you help me?
yeah @RioEduardo .i also mentioned this.
@user20232359723568423 - nah, that's the answer, thank you so much for helping :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.