Rikard
Rikard

Reputation: 7805

Control the order of the files with opendir() & readdir()

I checked at php.net opendir() but found no way to control the order of the files that opendir() gets.

I have a slideshow and I have problems controling the order of the images. I tried changing names and use 01.img,02.img,...,20.img but no sucess.

My script:

<?php
$path2 = "./img/";
function createDir($path2 = './img'){   
    if ($handle = opendir($path2)){
        echo "<ul class=\"ad-thumb-list\">";
        while (false !== ($file = readdir($handle))){
            if (is_dir($path2.$file) && $file != '.' && $file !='..')
                printSubDir($file, $path2, $queue);
            else if ($file != '.' && $file !='..')
                $queue[] = $file;
        }
        printQueue($queue, $path2);
        echo "</ul>";
    }
}

function printQueue($queue, $path2){
    foreach ($queue as $file){
        printFile($file, $path2);
    } 
}

function printFile($file, $path2){
    if ($file=="thumbs.db") {echo "";}
    else{
        echo "<li><a href=\"".$path2.$file."\">";
        echo "<img src=\"".$path2.$file."\" class='thumbnail'></a></li>";
    }
}

/*function printSubDir($dir, $path2)
{
}*/

createDir($path2);
?>

Upvotes: 0

Views: 330

Answers (3)

ComFreek
ComFreek

Reputation: 29424

Use scandir() and natsort().

Rewritten code:

function createDir($path2 = './img'){   
    $dirContents = scandir($path2);
    natsort($dirContents);

    echo "<ul class=\"ad-thumb-list\">";

    // You should actually add the line below!
    // $queue = array();    
    foreach ($dirContents as $entry) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }

      $entryPath = $path2 . $entry;
      if (is_dir($entryPath)) {
        printSubDir($entry, $path2, $queue);
      }
      else {
        $queue[] = $entry;
      }
    }
    printQueue($queue, $path2);
    echo "</ul>";
  }
}

Upvotes: 2

George Brighton
George Brighton

Reputation: 5151

As @Steven has already said, you may not be able to change the output of opendir(), but there's nothing stopping you from sorting the array afterwards.

To do this, have a look at the natsort() function, which is designed to properly sort strings like those you're using for file names.

Upvotes: 0

Will
Will

Reputation: 2333

If you are using PHP 5, you could try using scandir() instead. It has an argument for sorting.

https://www.php.net/scandir

array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

Upvotes: 1

Related Questions