I’m trying to consume an API delivering an object with a weird aggregation of the data it contains. So this disclaimer is in defence of the nested search you’re about to see. The API itself can be located here. Now the following code
- converts the response to an associative array containing some objects
- grabs teams from the objects and fetches another set of data (unfortunately, via a fresh API call)
The goal is to flush out some unwanted keys and index the data in a way that is easier for me to access.
$api = new FootballData();
$filter = ['timeFrameStart', 'timeFrameEnd', 'status', 'href', 'matchday', 'date', 'odds'/*, 'count'*/];
$compute = array();
$cascadingStats = array('goalsAwayTeam', 'goalsHomeTeam', 'result', 'halfTime');
$track = 0;
$response = @$api->fetchFixturesFor('n4');
$ironItOut = function ($obj, $index) use ($filter, &$ironItOut, $cascadingStats) {
foreach ($obj as $key => $value) {
if (is_object($value)) {
$ironItOut($value, $index);
}
elseif(!in_array($key, $filter)) {
if (in_array($key, $cascadingStats)) {
$compute[$index]['cascadingStats'][] = array($key => $value);
}
else {
$compute[$index][$key] = $value; // homeTeamName gets lost here. it's also a key
//echo("$key<br>"); //it magically appears here but isn't computed
}
}
}
};
try {
if ($response === FALSE) throw new Exception("Error Processing Request", 1);
}
catch (Exception $e) {
echo $e->getMessage();
}
$start = (int) explode(' ', microtime())[1];
foreach ($response->fixtures as $key => $fixtures) {
// for each pair, fetch their head to head
$id = $api->getFixtureId($fixtures->homeTeamName, $fixtures->awayTeamName, 'n4');
$h2h = $api->headToHead($id);
foreach($h2h as $key => $stdClass) {
if (isset($stdClass->count) && $stdClass->count > 2) {
$track++;
foreach ($stdClass as $key => $stats) {
if (is_a($stats, 'stdClass') || is_array($stats)) {
$compute[$track]['cascadingStats'] = []; // after hashing `cascadingStats` length and `count` should be equal
$ironItOut($stats, $track);
}
elseif(!in_array($key, $filter)) {
$compute[$track][$key] = $stats; // filter off undesirable keys
}
}
}
}
}
var_dump((int) explode(' ', microtime())[1] - $start, $compute);
The current code indexes all the keys as desired but leaves out some particular keys and I cannot figure out why. I need some extra pair of eyes to figure out if something is overwriting them or why they are disappearing. Thank you.