Home > Software design >  PHP - Trying to show Next and Previous file from the same directory
PHP - Trying to show Next and Previous file from the same directory

Time:07-03

As the title sais, I'm trying to get the next and previous file from the same directory. So I did some this like this. Is there any better way of doing it? (This is from next auto index file.php code about related files, I have change it for my needs.)

db screenshot if you want to look - ibb.co/wzkDxd3

$title = $file->name;   //get the current file name
$in_dir=$file->indir;   //current dir id
$r_file = $db->select("SELECT * FROM `". MAI_PREFIX ."files` WHERE `indir`='$in_dir'");  //all of the file from the current dir
$rcount=count($r_file);
$related='';
if($rcount > 2){
$i = 0; // temp variable
foreach($r_file as $key => $r){  //foreach the array to get the key
    if($r->name == $title){  //Trying to get the current file key number
        $next =$key 1; //Getting next and prev file key number
        $prv =$key-1;
        foreach($r_file as $keyy => $e){ //getting the file list again to get the prev file
            if($prv == $keyy){
                $related .=$e->name;
            }
        }
        foreach($r_file as $keyy => $e){ // same for the next file
            if($next == $keyy){
                $related .=$e->name;
            }
        }
    }
}

CodePudding user response:

Without knowing your DB background and use case, there still should be the possibility to use something like $r_file[$key], $r_file[$next] and $r_file[$prev] to directly access the specific elements. So at least two of your foreach loops could be avoided.

Please note, that nesting loops is extremely inefficient. E. g., if your $r_file contains 100 elements, this would mean 10.000 iterations (100 times 100) with your original code!

Also, you should leave a loop as soon as possible once its task is done. You can use break to do this.

Example, based on the relevant part of your code and how I understand it is supposed to work:

foreach($r_file as $key => $r){  //foreach the array to get the key

    if($r->name == $title) {  //Trying to get the current file key number
        $next =$key 1; //Getting next and prev file key number
        $prv =$key-1;
        $related .= $r_file[$prv]->name; //Directly accessing the previous file
        $related .= $r_file[$next]->name; //Directly accessing the next file
        break; // Don't go on with the rest of the elements, if we're already done
    }
   
}

Possibly, looping through all the elements to compare $r->name == $title could also be avoided by using some numbering mechanisms, but without knowing your system better, I can't tell anything more about that.

  •  Tags:  
  • php
  • Related