Mahfuz Shishir
Mahfuz Shishir

Reputation: 841

How to dynamically add attribute and value in json data

[{"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"}]

Upvotes: 1

Views: 1602

Answers (1)

wally
wally

Reputation: 3592

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);

Upvotes: 4

Related Questions