3

使用以下代码显示我的 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

4

2 回答 2

7

一个非常优雅的解决方案是使用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) {
    // ...
}
于 2009-11-05T11:06:50.077 回答
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 限制为数组长度,但希望您能理解要点。

于 2009-11-05T10:51:57.137 回答