1
[{"id":2,"name":"Paypal"},{"id":3,"name":"Scrill"}]

How to add dynamically new attribute and its value in here using php or in laravel framework. converted data is like

[{"id":2,"name":"Paypal","amount":"100"},{"id":3,"name":"Scrill","amount":"200"}]
6
  • 1
    What have you tried? Show us your attempt. Commented Sep 19, 2017 at 15:22
  • Actually i don't understand how to add new attribute here. Please give me a solution. Thanks for your comment. Commented Sep 19, 2017 at 15:25
  • 1
    Where have you researched? Commented Sep 19, 2017 at 15:26
  • I am not so expert so i asked here. Commented Sep 19, 2017 at 15:27
  • How much research effort is expected of Stack Overflow users? Commented Sep 19, 2017 at 15:27

1 Answer 1

4

In pseudo code:

Convert JSON string to PHP associative array.
Add / alter keys on PHP associative array.
Convert PHP associative array to JSON string.

I don't want to take all the fun away - so here are some links:

http://php.net/manual/en/function.json-decode.php

http://php.net/manual/en/function.json-encode.php

;-)


Update: OP has requested a complete solution.

To convert the JSON string to a PHP associative array:

$decoded = json_decode($jsonStr, true);

Always check that things didn't go wrong:

if ($decoded === null) {
   die('Unable to decode JSON string: ' . $jsonStr);
}

Modify your PHP array:

$decoded[] = array(
   'id' => 3,
   'name' => 'Scrill',
   'amount' => 200
);

Finally re-encode to a JSON string:

echo json_encode($decoded);
Sign up to request clarification or add additional context in comments.

3 Comments

i don't able to reach the solution until. Can you please give me solution?
@MahfuzShishir you can't do the research... what? Wally here has supplied you with EVERYTHING but actual code to learn for yourself. You're lucky you even had someone give you this much of a hint.
I find out the solution in another way.

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.