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

毎回完全なデータセットをロードしている場合は、それについてかなり直接的であり、foreach の代わりに for ループを使用できます。

$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 に答える