如何使用php过滤和重组json数据?

时间:2018-09-22 11:13:07

标签: php arrays json

我找不到答案,所以决定问。

我从API得到以下响应:

main :-
    current_prolog_flag(argv,[BB_S,CC_S]),
    atom_number(BB_S,BB),
    atom_number(CC_S,CC),
    comb(BB, CC, BF),
    print('Number of bracelets: '),
    write(BF),
    halt.

我正在尝试将json数据更改为此:

[
  {
      "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
   }
]

在当前代码中,我正在使用正则表达式,例如:

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

基本上是将所有内容放在一个单独的数组中,但这不是我想要的。

1 个答案:

答案 0 :(得分:3)

解码json,重组数据,重新编码。

代码:(Demo

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

输出:

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

p.s。如果要强制对象和精美打印,请使用竖线(|)分隔这些标志。 https://3v4l.org/qsPb0