Jump to content

Running into problems with sorting.


mikeyjai

Recommended Posts

hey it's me again! i got the function to run but there's some parts i don't quite understand. This function is the general directory listing. I would like to have it sort by file name but i don't know where to insert the sort function. Also, which exact code would i need to insert in order for it to run the way i want it to? The code is below

 

<?php
$sub = ($_GET['dir']);
$path = 'images';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
            if (substr($file, -4, -3) =="."){
            echo "$i. $file <br />";
            }else{            
        echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
          }
        $i++;
    }
}
closedir($dh);
?>

Link to comment
https://forums.phpfreaks.com/topic/99634-running-into-problems-with-sorting/
Share on other sites

The code is looping and reading each file in the directory one at a time and outputting it.

 

You need to redesign the code to perhaps hold each file entry in an array, then you might be able to use an array function like sort()

 

see also: http://au.php.net/manual/en/function.sort.php

 

Your code could look something like:

 

while (($file = readdir($dh)) !== false)
{
// code to prepare filenames for output
$arrayFiles[] = $file; // add file into files array
}
sort($arrayFiles);
foreach ($arrayFiles as $key => $value)
{
// output files to user
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.