开发者

PHP loop with set intervals

I have the following code that converts my twitter account rss feed into a string so that I can parse my followers user names.

$url = file_get_contents("MY_TWITTER_RSS_FEED_URL_GOES_HERE");
$source = simplexml_load_string($url);

foreach ($source as $match){

    //name of node
    $username = "&nbsp@".$match->author->name;
    //removes the name and parentheses ex.kyrober555 (Robert)
    $usernames = substr($username, 0, strpos($username, ' '));
    //returns usernames only ex.kyrober555
    echo $usernames;
    }

Using the foreach loop I return all 15 names from the feed and it looks like this.

 @ajay54 @marymary770 @funnigurl1209 @jimiwhitten @kyroberthl @tree_bear @crftyldy @sanbrt63 @Sandra516 @DreamFog @KravenSwagNBzz @DreamFog @TheCrippledDuck @TheCrippledDuck @Cass60

Now here is what I would like to do, but I am not sure if its possible, and I wouldn'y 开发者_如何学编程know how so I ask for your help. When I load the page for this php file it returns all user names at once. What I would like to do is return 5 user names then do something then return 5 more then do something else then return the last 5. Maybe something like this but I don't know...

foreach ($source as $match){
    /* Return the 1st 5 user names */

        /* do some other type of coding */

    /* Return the second set of 5 usernames */

        /* do something here */

    /* return the last 5 usernames */
    }

Ultimately returning all 15 user names, but at different intervals not all at once.


array_slice() is always nice. Something like this maybe:

for($offset = 0; $offset < count($array); $offset += 5){
    $slice = array_slice($array, $offset, 5);
    // Do your stuff
}


$count = 0;
foreach ($source as $match){
    $username = "&nbsp@".$match->author->name;
    $usernames = substr($username, 0, strpos($username, ' '));
    echo $usernames;
    if($count % 5 == 0 && $count > 0) {
        // do something else;
    } 
    $count++;
}

Thanks @vichle for you comment, maybe it's better to use a matrix then?

$count = 0;
$userArray = array();    
foreach ($source as $match){
    $username = "&nbsp@".$match->author->name;
    $usernames = substr($username, 0, strpos($username, ' '));
    $userArray[$count % 5][] = $usernames;
    $count++;
}

This code will probably need tweaking, but it's a start.. Now you've got an array within an array. $userArray[0] will return an array with the first 5 usernames, $userArray[1] will return an array with the second 5 usernames, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜