3

How to add Array Object and Data to JSON in Laravel

$json = {'id':5, 'name':'Hassan'};

I want to add new object role and value Admin to $json

I want result like

$json = {'id':5, 'name':'Hassan', 'role':'Admin'};

2 Answers 2

6

You could decode the JSON, add the values you want and then encode it back to JSON:

$data = json_decode($json, true);

$data['role'] = 'Admin';

$json = json_encode($json);

json_decode() Docs
json_encode() Docs

Sign up to request clarification or add additional context in comments.

Comments

3

Try this

$object = json_decode($json);
$object->role = 'Admin';
$json = json_encode($object)

Comments

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.