简体   繁体   中英

How to create a smart navigation with array in PHP or Javascript for previous and next?

I have a list of filenames

aeyrt.php
nviorf.php
vyutkd.php
oiuybd.php
poiuuy.php

Suppose that the current opened page is vyutkd.php

I have two arrows < and >

My question is how using PHP or Javascript the < will link to nviorf.php and the > to oiuybd.php ?

The same scenario goes if the current page is the first one. The < button should go to the last of the list.

Thank you

You could put the files name into an array:

$pages= Array( 'aeyrt.php','nviorf.php','vyutkd.php','oiuybd.php','poiuuy.php');

And create a function that check the current file name position and return a link to the previous or next page.

function getLink($pages,$previous = true){
 $position = array_search(basename(__FILE__),$pages);
 if($position==0 && $previous){
  return "<a href='".$pages[count($pages)-1]."'>Previous</a>";
 }
 if($position==count($pages)-1 && !$previous){
  return "<a href='".$pages[0]."'>Next</a>";
 }
 if($previous && $position!==null && $position>0){
  return "<a href='".$pages[$position-1]."'>Previous</a>";
 }
 if($position!==null && $position<count($pages)-1){
  return "<a href='".$pages[$position+1]."'>Next</a>";
 }
}

I did not check if it work, but I think so ;)

I modified the funtion to be circular

Would be something like this:

corrected code:

<?php
  $pages = array('aeyrt.php','nviorf.php','vyutkd.php','oiuybd.php','poiuuy.php');
  $current_file = basename(__FILE__);
  if(($current_id = array_search($current_file,$pages))){
     if($current_id == count($pages) - 1){
        echo "<a href=\"".$pages[$current_id -1]."\">previous</a>";
     }else{
        echo "<a href=\"".$pages[$current_id -1]."\">previous</a> <a href=\"".$pages[$current_id +1]."\">next</a>";
     }
  }else{
     echo "<a href=\"$pages[2]\">next</a>";
  }  
?>

But... I would personally put those links into database and use rewrite rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM