Reputation: 145
How can I sort a list of files & directories so directories are listed first in PHP??? I try natsort but it only sort alphabeticaly. My source:
$dirFiles = array();
$path = "./folder_path";
// opens images folder
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails" && $file != ".DS_Store") {
$isdir = $path . $file;
if(is_dir($isdir)){
$dirFiles[] = $file;
}
if(!is_dir($isdir)){
$dirFiles[] = $file;
}
}
}
closedir($handle);
}
natsort($dirFiles);
Listing files and directories
foreach($dirFiles as $file => $value)
{
$name = basename($value);
echo $name;
}
Upvotes: 2
Views: 222
Reputation: 20889
U can use a sort function with a default callback:
uasort($dirFiles, "folderFirstSort");
function folderFirstSort($a, $b){
if (is_dir($a) && !is_dir($b)){
//a is dir, should be "smaller"
return -1;
}else if (!is_dir($a) && is_dir($b)){
//b is dir, should be "smaller"
return 1;
}else{
//both are files OR folders, compare names
return strcmp($a,$b);
}
}
Maybe you need to swap the returns of -1
and 1
- i always confuse them and play arround until it matches the desired outcome :)
Upvotes: 0
Reputation: 81
You could make a multidimensional array:
if(is_dir($isdir)){
$dirFiles['dir'][] = $file;
}
if(!is_dir($isdir)){
$dirFiles['file'][] = $file;
}
To list files and directories:
ksort($dirFiles);
foreach($dirFiles as $files)
{
foreach($files as $file)
{
$name = basename($file);
echo $name;
}
}
Upvotes: 2