【问题标题】:How to Paginate lines in a foreach loop with PHP如何使用 PHP 在 foreach 循环中对行进行分页
【发布时间】:2010-12-13 08:49:19
【问题描述】:

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

$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>";
}

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

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

【问题讨论】:

  • 没有找到我要找的东西。只是如何为 mysql 结果执行此操作的示例。
  • 我担心我遗漏了一些东西,为什么在实际上并没有为每个项目循环时使用 foreach 循环很重要?

标签: php pagination simplexml


【解决方案1】:

一个非常优雅的解决方案是使用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) {
    // ...
}

【讨论】:

  • 我一直在看这个,看着它,但我仍然不明白如何使用它。对于初学者,使用您提供的以“//或更简洁”开头的示例 $offset 和 $count 定义在哪里?此外,允许访问者遍历分页数据的可见链接从何而来?这与我想做的非常相似(Paginate XML output),我只是不知道从哪里开始使用您提供的示例,如果您不介意使用更完整的代码更新您的示例一个将是最感激的。
【解决方案2】:

如果您每次都加载完整的数据集,您可以直接使用 for 循环而不是 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>";
}

您还需要将 $i 限制为数组长度,但希望您能理解要点。

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 2018-09-17
    • 2019-07-12
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多