duanhe4267 2018-09-22 11:13
浏览 391
已采纳

如何使用PHP过滤和重构json数据?

I couldn't find an answer, so I decided to ask.

I get this response from an API:

[
  {
      "seasonNumber":1,
      "numWins":1,
      "numHighBracket":2,
      "numLowBracket":2,
      "seasonXp":111,
      "seasonLevel":5,
      "bookXp":0,
      "bookLevel":1,
      "purchasedVIP":false
   },
   {
      "seasonNumber":2,
      "numWins":1,
      "numHighBracket":21,
      "numLowBracket":31,
      "seasonXp":1651,
      "seasonLevel":25,
      "bookXp":9,
      "bookLevel":11,
      "purchasedVIP":false
   },
   {
      "seasonNumber":3,
      "numWins":9,
      "numHighBracket":57,
      "numLowBracket":127,
      "seasonXp":4659,
      "seasonLevel":68,
      "bookXp":0,
      "bookLevel":100,
      "purchasedVIP":true
   },
   {
      "seasonNumber":4,
      "numWins":8,
      "numHighBracket":19,
      "numLowBracket":36,
      "seasonXp":274,
      "seasonLevel":33,
      "bookXp":7,
      "bookLevel":35,
      "purchasedVIP":true
   }
]

I am trying to change the json data to this:

{
  "seasons":
    [
      {
        "season":1,
        "battle_pass":false
      },
      {
        "season":2,
        "battle_pass":false
      },
      {
        "season":3,
        "battle_pass":true
      },
      {
        "season":4,
        "battle_pass":true
      }
    ]
}

In my current code I am using regex like this:

preg_match_all("/(?:\{\"seasonNumber\"\:(\w)|purchasedVIP\"\:(\w+))/", $response, $seasons);

echo '{"seasons":'.json_encode($seasons, JSON_FORCE_OBJECT, JSON_PRETTY_PRINT).'}';

It's basically putting everything in a separate array but that's not what I want.

  • 写回答

1条回答 默认 最新

  • dotws86260 2018-09-22 11:27
    关注

    Decode the json, restructure the data, re-encode.

    Code: (Demo)

    // your $json = 
    foreach (json_decode($json) as $set) {
        $array[] = ["season" => $set->seasonNumber, "battle_pass" => $set->purchasedVIP];
    }
    echo json_encode(["seasons" => $array]);
    

    Output:

    {"seasons":[{"season":1,"battle_pass":false},{"season":2,"battle_pass":false},{"season":3,"battle_pass":true},{"season":4,"battle_pass":true}]}
    

    p.s. if you want to force objects and pretty print, separate those flags with a pipe (|). https://3v4l.org/qsPb0

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

报告相同问题?

悬赏问题

  • ¥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系统搭建请教(跨境电商用途)