dongzongxun8491 2016-12-31 18:04
浏览 243
已采纳

更新存储在数据库中的JSON数据

I have JSON data that is stored in a variable which is a set of permissions for a particular user. The JSON data however, is not stored in a file, it's just in a database column.

I've tried to look for a method of updating a permission (which is either true or false) but I've had no luck thus far. At the moment, I have something to the effect of;

The raw JSON data...

{
    "permissions": {
        "permission_1": true,
        "permission_2": false
    }
}

Getting it out of the database...

$permissions = json_decode($data, true);

How do I (using PHP) update the JSON data to say, update permission 2 to true? I'm using json_decode() when it comes out of the database and putting it into an array but that's only for using it. After that I'm lost as to how to update the value.

  • 写回答

1条回答 默认 最新

  • duandingqi9442 2016-12-31 18:27
    关注

    In order:

    • Extract column data from the database.

      "SELECT column FROM table WHERE id = 1 LIMIT 1"       
      
    • JSON_decode data into a set of PHP values/objects/arrays/whatever.

      $array = json_decode($OutputRow['column'],true);
      
    • Update the value(s) you need to update.

      $array['permissions']['permission2'] = true;
      
    • Recompile into a JSON string using JSON_encode.

      $data = json_encode($array);
      
    • Update the database (SQL?) with the new JSON_encoded string.

      "UPDATE table SET column = :data WHERE id = 1 LIMIT 1"
      

    My examples use PDO and MySQL by reference but does not go into any details about database interaction as you've not given any details as to how you're reaching your database. It's only a ballpark rough example of how to do the points listed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)