我想按名称排序数组中的文件名,如Windows文件夹中的顺序

时间:2016-09-20 08:36:48

标签: php sorting directory filenames

如何按名称对数组中的文件名进行排序,例如在Windows文件夹中?代码和数组就像这样:

$arr =  array('php__01.png','php__02.png','php__03.png','php_2_01.png','php_2_02.png','php_10_01.png','php_10_02.png','php_9_02.png','php_9_01.png','php_9_03.png');
<?php
$arr =  array('php__01.png','php__02.png','php__03.png','php_2_01.png','php_2_02.png','php_10_01.png','php_10_02.png','php_9_02.png','php_9_01.png','php_9_03.png');
function cmp($a, $b) {
    $a_temp = str_replace('_', '', $a);
    $b_temp = str_replace('_', '', $b);     
    return strcmp($a_temp,$b_temp);
}
usort($arr, "cmp");
?>

像这样导出:

array(10) {
[0]=>
string(11) "php__01.png"
[1]=>
string(11) "php__02.png"
[2]=>
string(11) "php__03.png"
[3]=>
string(13) "php_10_01.png"
[4]=>
string(13) "php_10_02.png"
[5]=>
string(12) "php_2_01.png"
[6]=>
string(12) "php_2_02.png"
[7]=>
string(12) "php_9_01.png"
[8]=>
string(12) "php_9_02.png"
[9]=>
string(12) "php_9_03.png"
}

我希望这样排序:

array(10) {
[0]=>
string(10) "py__01.png"
[1]=>
string(10) "py__02.png"
[2]=>
string(10) "py__03.png"
[3]=>
string(11) "py_2_01.png"
[4]=>
string(11) "py_2_02.png"
[5]=>
string(11) "py_9_01.png"
[6]=>
string(11) "py_9_02.png"
[7]=>
string(11) "py_9_03.png"
[8]=>
string(12) "py_10_01.png"
[9]=>
string(12) "py_10_02.png"
}

2 个答案:

答案 0 :(得分:1)

您可以使用usort创建自定义排序功能;在这种情况下,依次按文件名的每个元素排序

$cb = function($valueA, $valueB) {
    $vA = explode('_', $valueA);
    $vB = explode('_', $valueB);
    $element = 0;
    do {
        $x = (int) $vA[$element] - (int) $vB[$element++];
    } while ($x == 0);
    return $x;
};

usort($arr, $cb);

答案 1 :(得分:1)

这是解决方案:

<?php
$arr =  array('php__01.png','php__02.png','php__03.png','php_2_01.png','php_2_02.png','php_10_01.png','php_10_02.png','php_9_02.png','php_9_01.png','php_9_03.png');
function reduce($a) {
    $a = str_replace('_', '-', $a);
    $a = preg_replace('#([0-9]+)#e', 'sprintf("%02d", "\\1")', $a);

    return $a;
}
function cmp($a, $b) {
    $a_temp = reduce($a);
    $b_temp = reduce($b);

    return strcmp($a_temp,$b_temp);
}
usort($arr, "cmp");
print_r($arr);
?>

http://ideone.com/Yt6jpQ

你需要替换&#34; _&#34; by&#34; - &#34;因为&#34; - &#34;订购号码时,char首先出现。

你还需要用前导零填充数字,这就是preg_match和sprintf的原因。

输出:

Array
(
    [0] => php__01.png
    [1] => php__02.png
    [2] => php__03.png
    [3] => php_2_01.png
    [4] => php_2_02.png
    [5] => php_9_01.png
    [6] => php_9_02.png
    [7] => php_9_03.png
    [8] => php_10_01.png
    [9] => php_10_02.png
)