2009-11-05 67 views
4

使用以下代碼從我的Twitter配置文件中顯示朋友列表。 Id喜歡每次只裝載一定數量,比如20,然後提供在底部的第一1-2-3-4-5(然而,許多通過限制分)最後分頁鏈接如何使用PHP在foreach循環中對行進行分頁

$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

+0

這已經被問了很多 - 例如參見http://stackoverflow.com/questions/163809/smart-pagination-algorithm – 2009-11-05 10:10:28

+0

Havnt發現什麼即時尋找。只是如何做到這一點的MySQL結果的例子。 – mrpatg 2009-11-05 10:41:14

+0

我很擔心我錯過了一些東西,爲什麼當你沒有實際循環每個項目時使用foreach循環是很重要的? – MalphasWats 2009-11-05 12:52:35

回答

8

一個非常優雅的解決方案是使用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

我一直在看這個,看着它,但我仍然不明白如何使用它。對於初學者,使用您提供的以「//或更簡潔」開頭的示例定義了$ offset和$ count的位置?此外,允許訪問者遍歷分頁數據的可見鏈接來自哪裏?這與我想要做的事情非常相似(Paginate XML輸出),我只是不知道從哪裏開始使用您提供的示例,如果您不介意使用更完整的代碼更新您的示例,人們會最感激。 – 2013-11-22 13:34:15

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限制到數組長度,但希望你能得到要點。