How to add Array Object and Data to JSON in Laravel

混江龙づ霸主 提交于 2021-02-10 18:51:45

问题


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'};


回答1:


Try this

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



回答2:


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



来源:https://stackoverflow.com/questions/55151044/how-to-add-array-object-and-data-to-json-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!