duandou2763 2019-06-09 17:24
浏览 94

我可以遍历一个元素数组,在每次迭代中发出一个GET请求,并以某种方式将GET结果映射到相应的元素吗?

$summonerMatches is an object that contains a property called matches which contains an array of objects. Each object contains information about the match like gameId.

enter image description here

In order to get the specific information about the match, I have to make a GET request using the gameId. I am currently looping through those matches and making a GET request to get the specific information about each match, however, I am wondering how to link the returned information to the respective match object inside the $summonerMatches object. In a way, I want to create a new property to each match and then assign it the result from the GET request in the loop.

$getSummonerMatches = file_get_contents($region . "/lol/match/v4/matchlists/by-account/gvgxEQIJUq3bvbR_oasXkFHY7oJ5G2WViBGVCL1eKGJXsg?startIndex=0&endIndex=10&api_key=" . $apiKey);
$summonerMatches = json_decode($getSummonerMatches);

foreach ($summonerMatches->matches as $match) {
    $getMatchInfo = file_get_contents($region . "/lol/match/v4/matches/" . $match->gameId . "?api_key=" . $apiKey);
    $matchInfo = json_decode($getMatchInfo);
}
  • 写回答

1条回答 默认 最新

  • dsxon40042 2019-06-09 17:57
    关注

    I don't see a reason not to set a new attribute called matchInfo on each object with the data retrieved from the API.

    <?php
    
    $getSummonerMatches = file_get_contents($region . "/lol/match/v4/matchlists/by-account/gvgxEQIJUq3bvbR_oasXkFHY7oJ5G2WViBGVCL1eKGJXsg?startIndex=0&endIndex=10&api_key=" . $apiKey);
    $summonerMatches = json_decode($getSummonerMatches);
    
    foreach ($summonerMatches->matches as &$match) {
        $getMatchInfo = file_get_contents($region . "/lol/match/v4/matches/" . $match->gameId . "?api_key=" . $apiKey);
        $matchInfo = json_decode($getMatchInfo);
        $match->matchInfo = $matchInfo;
    }
    

    Note that a & was added to foreach. This way, $match becomes a reference to the original object, and not a copy, thus keeping our changes outside the scope of the foreach.

    For a more ellegant approach, you can have each of these objects belonging to an actual class, and use a method to set the value, like addMatchInfo($matchInfo), instead of creating the attribute directly.

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?