opendir()具有分页支持

时间:2013-10-25 11:39:21

标签: php pagination

我有这个脚本:

<?php
if ($handle = opendir('konten')) {
    $blacklist = array('.', '..', 'somedir', 'index.php', 'style.css');
    while (false !== ($file = readdir($handle))) :
        if (!in_array($file, $blacklist)) :

?>
<div style="display:block;clear:both;">
<span style="font-size:18px;">&raquo;</span> <a href=""><?php echo $file;?></a>
</div>
<?php
endif;
endwhile;
closedir($handle);
}
?>

输出如下:

» linux (5th copy)
» linux
» linux (10th copy)
» linux (9th copy)
» linux (4th copy)
» linux (6th copy)
» linux (8th copy)
» linux (copy)
» linux (7th copy)
» linux (another copy)
» linux (3rd copy) 

如何添加分页?
例如。: 我想在一页上只显示3个目录。

1 个答案:

答案 0 :(得分:1)

实际上你需要设置限制和页面如下:

但在这种情况下,您将获得目录中的几乎所有文件。

<?php
$limit = 4; //Or just for dynamic limit - (int)$_GET['limit'];
$page = (int)$_GET['page']?:0; // _GET['page'] or 0 for default
$skip = $limit * $page;
if ($handle = opendir('konten')) {
    $blacklist = array('.', '..', 'somedir', 'index.php', 'style.css');
    $skiped = 0;
    while (false !== ($file = readdir($handle))) {
        if (!in_array($file, $blacklist)) { 
        $skipped++;
        if ($skipped < $skip || $skipped >= $skip + $limit) {
            continue;
        }
        ?>
            <div style="display:block;clear:both;">
                 <span style="font-size:18px;">&raquo;</span> <a href=""><?php echo $file;?></a>
             </div>           
       <?php }
    }
}
// For pagination support
$pages = (int)$skipped / $limit;
if ($skipped % $limit)
    $pages ++;

for ($i = 1; $i <= $pages; $i++) {
     $class = '';
     if ($page == $i) $class = 'class="active"';
    ?> <a href="?page=<?= $i ?>" <?= $class ?>><?= $i ?></a> <?php
}
?>

UPD:添加了分页支持