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

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历