如何使用PHP在foreach循环中对行进行分页 [英] How to Paginate lines in a foreach loop with PHP

查看:157
本文介绍了如何使用PHP在foreach循环中对行进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码显示我的Twitter个人资料中的朋友列表. 我想一次只加载一个特定的数字,例如20,然后在底部为第一页1-2-3-4-5(但除以限制)最后一页提供分页链接

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 bottom for First 1-2-3-4-5(however many divided by limit) Last

$xml = simplexml_load_string($rawxml);

foreach ($xml->id as $key => $value) 
{
    $profile           = simplexml_load_file("https://twitter.com/users/$value");
    $friendscreenname  = $profile->{"screen_name"};
    $profile_image_url = $profile->{"profile_image_url"};

    echo "<a href=$profile_image_url>$friendscreenname</a><br>";
}

******更新******

******update******

if (!isset($_GET['i'])) {
    $i = 0;
} else {
    $i = (int) $_GET['i'];
}

$limit  = $i + 10;
$rawxml = OauthGetFriends($consumerkey, $consumersecret, $credarray[0], $credarray[1]);
$xml    = simplexml_load_string($rawxml);

foreach ($xml->id as $key => $value)
{

    if ($i >= $limit) {
        break;
    }

    $i++;
    $profile           = simplexml_load_file("https://twitter.com/users/$value");
    $friendscreenname  = $profile->{"screen_name"};
    $profile_image_url = $profile->{"profile_image_url"};

    echo "<a href=$profile_image_url>$friendscreenname</a><br>";
}

echo "<a href=step3.php?i=$i>Next 10</a><br>";

这有效,只需要偏移从$i开始的输出即可.正在考虑array_slice?

This works, just have to offset the output starting at $i. Thinking array_slice?

推荐答案

一个非常优雅的解决方案是使用 LimitIterator :

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) {
    // ...
}

这篇关于如何使用PHP在foreach循环中对行进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆