PHP按文件名对数组进行排序


PHP sort array by filename

下面的代码扫描当前文件夹中的word文档,然后吐出它找到的所有文档的数组。。。。

<?php
    $a=array();
    if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
    if(preg_match("/'.doc$/", $file)) 
    $a[]=$file;
    }
    closedir($handle);
    }
    foreach($a as $i){
    echo $i;
    }
?>

这一切都很好,但订单不是我想要的。有没有办法按文件名对结果进行排序?我看过排序函数,但不知道如何在我的情况下实现它。

您可以使用glob(),它将自动为您排序:

$files = glob('*.doc');

有关更多详细信息,请参阅glob()上的PHP。

如果顺序不是预期的顺序,则传递参数GLOB_NOSORT以按文件在目录中的显示顺序返回文件。

您可以使用sort()

它在适当的位置进行操作,所以您不会将排序后的数组作为返回值。

<?php
    $a=array();
    if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
    if(preg_match("/'.doc$/", $file)) 
    $a[]=$file;
    }
    closedir($handle);
    }
    sort($a);
    foreach($a as $i){
    echo $i;
    }
?>