如何在PHP中显示文件夹中的next和prev导航?

问题描述:

I need to create a previous and next navigation in one folder using a structure like page 1 page 2 etc My current not-working code is the following:

<?php 
    $search_dir = "gallery";
    $images = glob("$search_dir/*.jpg");
    sort($images);
    $current = 2;
    $prev_img = $images[$current - 1];
    $next_img = $images[$current + 1];
    // Image selection and display:

    //display first image
    if (count($images) > 0) { // make sure at least one image exists
        $img = $images[0]; // first image 
        ?>
        <ul>
            <li><a href="<?php echo $prev_img; ?>">Previous</a></li>
            <li><a href="<?php echo $next_img; ?>">Next</a></li>
        </ul>
        <figure><img src="<?php echo $img; ?>" alt="<?php echo $img; ?>"></figure>
    <?php 
        } else {
      echo 'error';
    }
?>

I am bit in hurry please try this code i have made some correction please look into the code, try to understand.

<?php 
    $search_dir = "gallery";
    $images = glob("$search_dir/*.jpg");
    sort($images);
    if(isset($_REQUEST['image_no']))
    {
        $image_no = $_REQUEST['image_no'];    
    }
    else
    {
        $image_no = 2;
    }

    $prev_img = ($image_no == 0)?(count($images)-1):($image_no -1);
    $next_img = ($image_no == count($images)-1)?0:($image_no + 1);
    // Image selection and display:

    //display first image
    if (count($images) > 0) { // make sure at least one image exists
        $img = $images[$image_no]; // first image 
        ?>
        <ul>
            <li><a href="gallery.php?image_no=<?php echo $prev_img; ?>">Previous</a></li>
            <li><a href="gallery.php?image_no=<?php echo $next_img; ?>">Next</a></li>
        </ul>
        <figure><img src="<?php echo $img; ?>" alt="<?php echo $img; ?>"></figure>
    <?php 
        } else {
      echo 'error';
    }
?>