How to add Pagination in scandir() php [closed]

2019-07-10 00:18发布

问题:

I want to add pagination my 'scandir' php code , please help me how to add pagination in my php code

here is my code

    <?

// image extensions
$extensions = array('3gp', 'mp4', 'png', 'gif', 'bmp');

// init result
$result = array();

// directory to scan
$directory = new DirectoryIterator('files/'.$_GET['dir'].'');

// iterate
foreach ($directory as $fileinfo) {
    // must be a file
    if ($fileinfo->isFile()) {
        // file extension
        $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
        // check if extension match
        if (in_array($extension, $extensions)) {
            // add to result
            $result[] = $fileinfo->getFilename();
        }
    }
}
// print result

foreach($result as $files)
{

    echo "<div class='fl odd".(++$j%2==0 ? "2" : "")."'>";
    echo '<a class="fileName" href="file.php?file=files/'.$_GET['dir'].'/'.$files.'"><div><div><img src="thumb.php?dir=files/'.$_GET['dir'].'/'.$files.'" width="80" height="80" alt="'.$files.'" /></div><div>'.$files.'<br/><span>[Size : 32.74Mb]</span><br/></div></div></a></div>';}

Now , please explain me how to add Pagination (Pages) in this code , i want to show 10 results per pag.

回答1:

Try this example:

let's say we have index.php file

$perpage = 10;
$page = (int)$_GET['page'];
if(!($page>0)) $page = 1;
$offset = ($page-1)*$perpage;

$extensions = array('3gp', 'mp4', 'png', 'gif', 'bmp');
$files = glob('files/'.$_GET['dir'].'/*.'.'{'.implode(',', $extensions).'}', GLOB_BRACE);
$total_files = sizeof($files);
$total_pages = ceil($total_files/$perpage);
$files = array_slice($files, $offset, $perpage);
?>

<div>
    SHOWING: <?=$offset?>-<?=($offset+$perpage)?>  of <?=$total_files?> files
</div>

<?php foreach($files AS $file) : ?>
    <a class="fileName" href="file.php?file=files/<?=$_GET['dir']?>/<?=basename($file)?>">
        <?=basename($file)?>
    </a>
<?php endforeach; ?>




<a class="page" href="index.php?dir=<?=$_GET['dir']?>&page=<?=(($page-1>1)?($page-1):1)?>">
   <<
</a>

<?php for($p=1; $p<=$total_pages; $p++) : ?>
    <a class="page" href="index.php?dir=<?=$_GET['dir']?>&page=<?=$p?>">
        <?=$p?>
    </a>
<?php endfor; ?>

<a class="page" href="index.php?dir=<?=$_GET['dir']?>&page=<?=(($page+1>$total_pages)?$total_pages:($page+1)?>">
   >>
</a>


回答2:

It may working but you need to do some changes as your code

$page_number = 1;
$count = 10;
$start_from = ($page_number - 1) * 10;
$end = $start_from + $count;

display array values from $result[$start_from] to $result[$end] using any loop.

Set and send next $page_number from displaying area to your function....