0

I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.

`

//Open images directory
$dir = opendir("../blogimg/luda_jesus");


//List files in images directoryb
while (($file = readdir($dir)) !== false)
  {
      if(substr( $file, -3 ) == "jpg" )

      {
        echo "<div class='container'><img class='lazy' id='background'  src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";

        //echo "<br />";

      }
  }

closedir($dir);

?>` 

Please help me

user1698200
  • 1
  • 1
  • 2
  • How are the filenames constructed? Any way, take a look here http://stackoverflow.com/questions/541510/php-readdir-not-returning-files-in-alphabetical-order – Dennis Hunink Apr 06 '13 at 18:44

2 Answers2

1

You can do this much more easily with glob:

$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
    echo '...';
}

I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.

Example:

//Open images directory
$dir = opendir("../blogimg/luda_jesus");

//List files in images directoryb
while (($file = readdir($dir)) !== false) {
   if(substr( $file, -3 ) == "jpg" ) { 
     $filelist[] = $file;
   }
}

closedir($dir);
sort($filelist);

for($i=0; $i<count($filelist)-1; $i++) {
  echo "<div class='container'>
    <img class='lazy' id='background'  
      src='../blogimg/loader.gif' 
      data-original='../blogimg/luda_jesus/" . $file . "' 
      width='884' height='587'>
   </div>";
}

If you require different means of sorting, please mention so.

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56