Reputation: 13843
I have the following code which outputs the contents of text files held in a directory.
Ive been looking at the sort
command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.
How can I sort the directory of file before they are output?
$directory = "polls/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
}
}
closedir($dir);
Upvotes: 0
Views: 121
Reputation: 146558
Another possibility is fetching the file names with glob(). Its output is sorted by default.
<?php
foreach(glob('polls/*.txt') as $file){
// ...
}
?>
Upvotes: 1
Reputation: 1540
Don't print it in the while loop, but store it in an array. Sort the array and then print it.
(On php.net you'll find enough different sorting functions to get the sorting method you need.)
Upvotes: 0
Reputation: 655519
First collect the entries in an array, sort it and then put it out:
$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
foreach ($files as $file) {
// content of your original while loop
}
Upvotes: 3