$dirct= $_SERVER['DOCUMENT_ROOT'].'/main/'; $hdl=opendir($dirct); while ($file = readdir($hdl)) if ( ($file!=".")&&($file!="..")) { $a[]=$file; } closedir($hdl); foreach ($a as $value) { echo ("<a href = /main/$value>$value</a><br/>") ; } 

How to sort the array $a so that the folders were above the files and everything is in alphabetical order? Using the function uksort , but I don’t know how.

    2 answers 2

     $dirs = []; $files = []; ... if (($file!=".")&&($file!="..")){ if(is_dir($file)) $dirs[]=$file; else $files[] = $file; } //сортировка sort'ΠΎΠΌ ΠΈ Π²Ρ‹Π²ΠΎΠ΄ ΠΈΠ· $dirs, Π·Π°Ρ‚Π΅ΠΌ ΠΈΠ· $files 

      You can use the filesize($file) function to check whether we are dealing with a category or file. Your example in this case will look like this:

       $dirct= $_SERVER['DOCUMENT_ROOT'].'/main/'; $hdl=opendir($dirct); while ($file = readdir($hdl)) if ( ($file!=".")&&($file!="..")) { if(filesize($file)) $files[]=$file; else $dirs[] = $file; } closedir($hdl); usort($files,"strcmp"); //Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Ρ„Π°ΠΉΠ»Ρ‹ foreach ($files as $value) { echo ("<a href = /main/$value>".$value."</a><br/>") ; } //Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΠΈ usort($dirs,"strcmp"); foreach ($dirs as $value) { echo ("<a href = /main/$value>".$value."</a><br/>") ; } 

      You can also add the use of the usort () function; Like this:

       function mySort($file_a, $file_b){ //функция для сортировки элСмСнтов //Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚: //-1 Ссли $file_a Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ Π½ΠΈΠΆΠ΅ Ρ‡Π΅ΠΌ $file_b // 1 Π² ΠΎΠ±Ρ€Π°Ρ‚Π½ΠΎΠΉ ситуации // 0 Ссли элСмСнты эквивалСнтны $filesize_a = filesize($file_a); $filesize_b = filesize($file_b); if (!$filesize_a && !$filesize_b || $filesize_a && $filesize_b) return strcmp($file_a, $file_b); else if ($filesize_a) return -1; else return 1; } $dirct= $_SERVER['DOCUMENT_ROOT'].'/main/'; $hdl=opendir($dirct); while ($file = readdir($hdl)) if ( ($file!=".")&&($file!="..")) { $a[]=$file; } closedir($hdl); usort($a,"mySort"); foreach ($a as $value) { echo ("<a href = /main/".$value.">".$value."</a><br/>") ; } 

      This code will display links to files first, then to folders. Playing with the values ​​returned by the mySort () function, you can change the sorting.