Home Loop while changing the name of a variable
Reply: 1

Loop while changing the name of a variable

Stephen Redding
1#
Stephen Redding Published in 2018-02-12 23:12:58Z

Using FaceBook PHP SDK, when I want to get the next page of results I call something along the likes of $next = $fb->next($response). Now for the next page, I would have to call $next2 = $fb->next($next). I want to put this into a loop as obviously, I will never know beforehand how many times to execute this until I get through all the pages of results. When there are no more pages, the $fb->next() call will = null.

Here is an example without a loop:

$reactions = array();
$response = $response->getGraphEdge();

foreach ($response as $reaction) {
    $reactions[] = $reaction['name'] . " - " . $reaction['type'];
}

$next = $fb->next($response);
foreach ($next as $reaction) {
    $reactions[] = $reaction['name'] . " - " . $reaction['type'];
}

$next2 = $fb->next($next);
foreach ($next2 as $reaction) {
    $reactions[] = $reaction['name'] . " - " . $reaction['type'];
}

$next3 = $fb->next($next2);
foreach ($next2 as $reaction) {
    $reactions[] = $reaction['name'] . " - " . $reaction['type'];
}

print_r($reactions);
Stephen Redding
2#
Stephen Redding Reply to 2018-02-14 17:45:16Z

I was over-complicating this.. I didnt account for the fact that if I keep the variable name the same it gets updated on each iteration of a loop. So this worked:

                $reactions = array();
                $response = $response->getGraphEdge();

                if ($fb->next($response) == null) {

                    foreach ($response as $reaction) {
                        $reactions[] = $reaction['name'] . " - " . $reaction['type'];
                    }

                }else {

                    foreach ($response as $reaction) {
                        $reactions[] = $reaction['name'] . " - " . $reaction['type'];
                    }

                    while ($response = $fb->next($response)) {

                        foreach ($response as $reaction) {
                            $reactions[] = $reaction['name'] . " - " . $reaction['type'];
                        }

                    }

                }

                echo "<pre>";
                print_r($reactions);
                echo "</pre>";
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.35096 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO