繁体   English   中英

用PHP数组重建Json响应

[英]Rebuild Json response with php array

我从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 ...

此响应有多个游戏(上面的响应只是一个游戏)。 我有一个可与其他API配合使用的iOS应用(我不想更改应用代码)。 旧的应用程序将所有游戏都放在这样的数组中:

"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做到这一点?

您将需要解码json响应,并将其放入以“ matches”为键的新数组,如下所示:

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

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

不要以为你将需要foreach这里,但我可能没有完全理解你。 首先,要使用json_decode将json解码为PHP数组,然后创建一个新数组,并将第一个解码后的数组放入json_decode 例:

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

如果您现在要初始化该数组,则只需将$games["matches"]放入foreach中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM