2012-03-31 124 views
0

我有這樣的代碼,顯示內部「圖片」目錄中的所有圖像,但它是非常惱人的,因爲所有的圖像都顯示在一個頁面上:/分支圖像結果分成多頁

我怎麼能在分割這些圖像多個頁面?

這裏是代碼

<html> 
<head> 
<link rel="stylesheet" href="style.css" type="text/css" media="screen" /> 
</head> 
<?php 
$files = glob("images/*.*"); 
echo '<div id="design">'; 

for ($i=0; $i<count($files); $i++) { 
    $num = $files[$i]; 
     if ($i%3==0){echo '<div class="Row">';} 
     echo '<img class="img" width="250px" height="250px" src="'.$num.'" alt="random image" />'; 
     if ($i%3==0){echo '</div>';} 
    } 

echo '</div>'; 
?> 
+1

看看分頁:http://phpeasystep.com/phptu/29.html – 2012-03-31 13:51:58

回答

1

首先,嘗試用更多的東西代替這條線。這將返回所有文件(圖像或其他任何東西),除非您確信只有圖像文件夾中:

$files = glob("images/*.*"); 

$files將導致與路徑圖像陣列,您可以輕鬆地使用此功能僅顯示您想要在頁面中顯示的圖像數量。

這樣的:

<?php  

$imagesPerPage = 10; 

if(!isset($_GET["start"])) 
{ 
    $start = 0; 
} 
else 
{ 
    $start = $_GET["start"]; 
} 

$files = glob("images/*.*");  

for($i = $start; $i < $start + $imagesPerPage; $i++) 
{ 
    if(isset($files[$i])) 
    { 
     echo "<img src=\"".$files[$i]."\" width=\"100\" height=\"100\" />\r\n"; 
    } 
} 

$start = $start + $imagesPerPage;  

echo "<br />\r\n"; 
echo "<a href=\"index.php?start={$start}\">NEXT</a>"; 
?>  

您可以遵循相同的規則,使透水鏈接以及!

請注意,停止(禁用)NEXT或Pervious鏈接取決於您自己!

2

分頁!這裏有一個出發點:

// glob list of images 
$files = glob('images/*'); 

// for consistency, you'll have to sort the resulting array... 
natcasesort($files); 

// get a page number from a query string e.g: ?page=1 
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT); 

// filter_input returns null if there is no page value in the qs, 
// so let's check that and add a default value if we need to 
$page = $page ?: 1; 

// slice the array! get a subset of the files array based on 
// an offset (page number) and length (results per page) 
$resultsPerPage = 5; 
$slice = array_slice($files, (($page - 1) * $resultsPerPage), $resultsPerPage); 

您現在可以正常顯示結果子集。當然,您必須爲每個頁面提供一系列鏈接......這很簡單:獲取$files陣列的長度,並使用您的$resultsPerPage值來確定需要顯示多少頁面。

希望這會有所幫助:)

+0

快速提示:三元快捷方式'$ page = $ page?:1;'是一個PHP> = 5.3的特性;如果你使用的是<= 5.2,那麼用'if(null === $ page)$ page = 1;'或者其他來替換它。 – 2012-03-31 14:18:37

+2

對於'filter_input()',+1,我不知道。 – shanethehat 2012-03-31 14:22:23

+0

不客氣:)它非常整齊。很多很棒的過濾選項。幫助刪除了一些驗證樣板! – 2012-03-31 14:23:53