简体   繁体   中英

List all files and folders in order using PHP

My code:

<?php

$dirs = array_filter(glob('*'), 'is_dir');
$files = array_filter(glob('*'), 'is_file');
$all = $dirs + $files;

foreach ($all as $value){
    echo '<li><a href="'.$value.'">'.$value.'</a></li>'; 
}
?>

This returns all files and folders but in random order:

Array
(
    [2] => New folder
    [6] => dir
    [7] => dir1
    [8] => dir2
    [9] => dir3
    [0] => A_test.txt
    [1] => Index.php
    [3] => app.exe
    [4] => b_test
    [5] => delete.php
    [10] => hello.png
    [11] => z_test.txt
)

sort() doesn't work. I want to sort them like default order.

Just like Half Crazed mentioned, you are just missing the sort() of the files before echoing them.

<?php

$dirs = array_filter(glob('*'), 'is_dir');
$files = array_filter(glob('*'), 'is_file');
$all = $dirs + $files;

sort($all); //sort them

foreach ($all as $value){
    echo '<li><a href="'.$value.'">'.$value.'</a></li>'; 
}

?>

They aren't really in random order. The default behavior of glob is to sort the names it returns. You actually have to use GLOB_NOSORT flag to override this if you don't want them sorted. They look random because the sort is case sensitive, and uppercase names appear at the top. If you want to sort them case-insensitively, use natcasesort on your two arrays before you combine them.

$dirs = array_filter(glob('*'), 'is_dir');
natcasesort($dirs);
$files = array_filter(glob('*'), 'is_file');
natcasesort($files);
$all = $dirs + $files;

foreach ($all as $value){
    echo '<li><a href="'.$value.'">'.$value.'</a></li>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM