Question

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.

Was it helpful?

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>";
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top