用php数组重建Json响应

时间:2016-04-21 14:31:07

标签: php arrays json api

我从JSON的API中获取了一些数据。典型的回答如下:

[
  {
    "id": "1918443",
    "comp_id": "1322",
    "formatted_date": "20.04.2016",
    "season": "2015/2016",
    "week": "32",
    "venue": "De Grolsch Veste (Enschede)",
    "venue_id": "1067",
    "venue_city": "Enschede",
    "status": "FT",
    "timer": "",
    "time": "18:45",
    "localteam_id": "13460",
    "localteam_name": "Twente",
    "localteam_score": "2",
    "visitorteam_id": "13253",
    "visitorteam_name": "Excelsior",
    "visitorteam_score": "0",
    "ht_score": "[0-0]",
    "ft_score": "[2-0]",
    "et_score": null,
    "penalty_local": null,
    "penalty_visitor": null, 

etc ...

此回复有多​​个游戏(上述回复只有一个游戏)。 我有一个iOS应用程序可以与其他API一起使用(我不想更改应用程序代码)。旧的应用程序将所有游戏都放在这样的数组中:

"matches": [
    {
    "id": "1918443",
    "comp_id": "1322",
    "formatted_date": "20.04.2016",
    "season": "2015/2016",
    "week": "32",
    "venue": "De Grolsch Veste (Enschede)",
    "venue_id": "1067",
    "venue_city": "Enschede",
    "status": "FT",
    "timer": "",
    "time": "18:45",
    "localteam_id": "13460",
    "localteam_name": "Twente",
    "localteam_score": "2",
    "visitorteam_id": "13253",
    "visitorteam_name": "Excelsior",
    "visitorteam_score": "0",
    "ht_score": "[0-0]",
    "ft_score": "[2-0]",
    "et_score": null,
    "penalty_local": null,
    "penalty_visitor": null, 

所以我想做的是将第一个JSON响应放入数组中“匹配”我如何使用foreach执行此操作?

2 个答案:

答案 0 :(得分:0)

您将需要解码json响应并将其放入一个新的数组中,该数组使用'匹配'像这样:

$json = //... your json response here
$games = ['matches' => json_decode($json, true)];

foreach ($games as $game) {
    // ...
}

答案 1 :(得分:0)

不要认为你需要foreach,但我可能完全不了解你。首先要做的是使用json_decode将json解码为PHP数组,然后创建一个新数组并将第一个解码后的数组放入匹配。例如:

$gameData = json_decode(/* your json string from above */);
$games = [
    "matches" => $gameData
];
echo json_encode($matches);

如果您现在要使用此数组,只需将$games["matches"]放入foreach。