Kash
Kash

Reputation: 1801

Using do while loop inside a foreach

I am doing this call to soccer api inside a foreach loop to return each competition matches. This call works just fine if it's outside a foreach loop. When in foreach I only get the first competition array but then the array is not reseted! it keeps returning the same results for the first loop, I tried to unset the variables but that does not seem to work. any idea?

foreach($comps as $comp){
    $comp_api = $comp->comp_id;
    $from_date = new datetime($start_date);
    $to_date = new datetime($end_date);
    $matches_setup = ['query' => ['leagues' => $comp_id]];

    #loop matches
    $matches = array();
    do {
        $matches = array_merge($matches, $api->fixtures()->between()->period($from_date, $to_date, null, $matches_setup));
    } while ($monk_framework->fixtures()->nextPage($matches_setup));
    $results = $matches;

    /*
    * part where data is inserted to db
    */
}

Is there something wrong with how am doing it? or this could be an issue with the api?

Upvotes: 0

Views: 745

Answers (2)

Kash
Kash

Reputation: 1801

I found a solution, and figured what was wrong.

while ($monk_framework->fixtures()->nextPage($matches_setup));

This part the params of nextPage used not to reset after each loop, it's a miss configuration in the api am using. resetting the params after each loop helped solve my issue.

#reset params for next call
self::$param = array();

For anyone who might stumble on this issue on the same framework of sportmonks, here is full details to the issue.

Upvotes: 0

Jim Wright
Jim Wright

Reputation: 6058

It looks like you are resetting your results on each loop.

You should append to results each iteration:

$results = [];

foreach($comps as $comp){

    $from_date = new datetime($start_date);
    $to_date = new datetime($end_date);
    $matches_setup = [
        'query' => [
            'leagues' => $comp_id
        ]
    ];

    #loop matches
    $matches = array();
    while ($api->fixtures()->nextPage($matches_setup)) {
        $matches = array_merge($matches, $api->fixtures()->between()->period($from_date, $to_date, null, $matches_setup));
    }
    $results = array_merge($results, $matches);
}

Upvotes: 1

Related Questions