我可以遍历一个元素数组,在每次迭代中发出一个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);
}

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.