How to Paginate lines in a foreach loop with PHP

前端 未结 2 1971
萌比男神i
萌比男神i 2020-11-30 11:51

Using the following code to display a list of friends from my twitter profile. Id like to only load a certain number at a time, say 20, then provide pagination links at the

相关标签:
2条回答
  • 2020-11-30 12:36

    If you're loading the full dataset every time, you could be pretty direct about it and use a for loop instead of a foreach:

    $NUM_PER_PAGE = 20;
    
    $firstIndex = ($page-1) * $NUM_PER_PAGE;
    
    $xml = simplexml_load_string($rawxml);
    for($i=$firstIndex; $i<($firstIndex+$NUM_PER_PAGE); $i++)
    {
            $profile = simplexml_load_file("https://twitter.com/users/".$xml->id[$i]);
            $friendscreenname = $profile->{"screen_name"};
            $profile_image_url = $profile->{"profile_image_url"};
            echo "<a href=$profile_image_url>$friendscreenname</a><br>";
    }
    

    You'll also need to limit $i to the array length, but hopefully you get the gist.

    0 讨论(0)
  • 2020-11-30 12:50

    A very elegant solution is using a LimitIterator:

    $xml = simplexml_load_string($rawxml);
    // can be combined into one line
    $ids = $xml->xpath('id'); // we have an array here
    $idIterator = new ArrayIterator($ids);
    $limitIterator = new LimitIterator($idIterator, $offset, $count);
    foreach($limitIterator as $value) {
        // ...
    }
    
    // or more concise
    $xml = simplexml_load_string($rawxml);
    $ids = new LimitIterator(new ArrayIterator($xml->xpath('id')), $offset, $count);
    foreach($ids as $value) {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题