1

Using WAMP, I'm trying to make PHP sort the same way as Windows using the following code:

<?php
    $folder = opendir("folderx");
    $fileNameList = array();

    while(false !== ($fileName = readdir($folder))){
        array_push($fileNameList, $fileName);
    }

    echo "<pre>";
    print_r($fileNameList);
    echo "</pre>";
?>

However, I'm getting weird results. This is how PHP is sorting:

Array
(
[0] => .
[1] => ..
[2] => New Text Document - Copy (2) - Copy - Copy.txt
[3] => New Text Document - Copy (2) - Copy.txt
[4] => New Text Document - Copy (2).txt
[5] => New Text Document - Copy (3) - Copy.txt
[6] => New Text Document - Copy (3).txt
[7] => New Text Document - Copy (4) - Copy.txt
[8] => New Text Document - Copy (4).txt
[9] => New Text Document - Copy - Copy (2) - Copy.txt
[10] => New Text Document - Copy - Copy (2).txt
[11] => New Text Document - Copy - Copy (3).txt
[12] => New Text Document - Copy - Copy - Copy (2).txt
[13] => New Text Document - Copy - Copy - Copy - Copy.txt
[14] => New Text Document - Copy - Copy - Copy.txt
[15] => New Text Document - Copy - Copy.txt
[16] => New Text Document - Copy.txt
[17] => New Text Document.txt
)

And this is how Windows is sorting:

enter image description here

4

2 回答 2

2

如果您使用 natcasesort($fileNameList) 对数组进行排序,如下所示:

<?php
$folder = opendir("folderx");
$fileNameList = array();

while(false !== ($fileName = readdir($folder))){
    array_push($fileNameList, $fileName);
}

function strip_non_cmp_characters($word) {
    return str_replace(array("(",")"," ","."),array("","","",""), $word);
}

function wincmp($a,$b) {
    return strnatcasecmp(strip_non_cmp_characters($a),
        strip_non_cmp_characters($b));
}

usort($fileNameList,"wincmp");

echo "<pre>";
print_r($fileNameList);
echo "</pre>";
于 2013-06-22T19:47:41.770 回答
0

您可以使用scandir按字母顺序对文件进行排序。Opendir 以它们存储在文件系统中的方式返回它们,而不是它们在 Windows 中显示的方式。

于 2013-06-22T19:52:58.273 回答