Search code examples
phpsortingreaddir

Readdir images from subdirectories and SORT alphabetically?


i found this code (https://stackoverflow.com/a/9628457/1510766) for show all images from directories and sub-directories, and works fine, but im trying to implement the sort() function of php but doesnt work:

    function ListFiles($dir) {
        if($dh = opendir($dir)) {
            $files = Array();
            $inner_files = Array();
            while($file = readdir($dh)) {
                if($file != "." && $file != ".." && $file[0] != '.') {
                    if(is_dir($dir . "/" . $file)) {
                        $inner_files = ListFiles($dir . "/" . $file);
                        if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
                    } else {
                        array_push($files, $dir . "/" . $file);
                    }
                }
            }
            closedir($dh);

            // -- SORTING the FILES --
            sort($files);

            return $files;
        }
    }

    foreach (ListFiles('works/'.$service_get_var.'/') as $key=>$file){
        echo "<li><img src=\"$file\"/></li>";
    }

When I test this, I cant see any images, is the correct use for sort()?. Thank you very much.


Solution

  • Sort after read all, not in recursive steps

    function ListFiles($dir) {
            if($dh = opendir($dir)) {
                $files = Array();
                $inner_files = Array();
                while($file = readdir($dh)) {
                    if($file != "." && $file != ".." && $file[0] != '.') {
                        if(is_dir($dir . "/" . $file)) {
                            $inner_files = ListFiles($dir . "/" . $file);
                            if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
                        } else {
                            array_push($files, $dir . "/" . $file);
                        }
                    }
                }
                closedir($dh);
    
                // -- SORTING the FILES --
                //sort($files);
    
                return $files;
            }
        }
    
        $list = ListFiles('works/'.$service_get_var.'/');
        sort($list);
        foreach ($list as $key=>$file){
            echo "<li><img src=\"$file\"/></li>";
        }