duan5362
2019-03-13 20:54
浏览 486
已采纳

如何在Laravel中将数组对象和数据添加到JSON

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

图片转代码服务由CSDN问答提供 功能建议

如何在Laravel中将数组对象和数据添加到JSON

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

我想添加新对象 role 和 值 Admin $ json

我想要结果如

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsuikgi9199 2019-03-13 21:00
    已采纳

    Try this

    $object = json_decode($json);
    $object->role = 'Admin';
    $json = json_encode($object)
    
    点赞 评论
  • doson1998 2019-03-13 20:59

    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

    点赞 评论

相关推荐 更多相似问题