Php按文件名排序

时间:2014-11-29 14:43:58

标签: php sorting

我有这段代码

if($dateOrder){
    $order = array(filemtime($filter_files[0]));
    for($i=1;$i<$maxnr+1;$i++){
        array_push($order,filemtime($filter_files[$i]));
    }
    array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
}
}
//end get image files

如何按文件名排序?例如

picture1,picture2,picture3 picture10,picture11

1 个答案:

答案 0 :(得分:1)

根据我的建议,这是工作代码。与代码的不同之处在于array_multisort方法的用法。 PHP array_multiosrt期望将单维非关联数组作为其第一维和第二维,然后将整个数据数组作为最后一个参数。

<?php
    $dateOrder = true;
    if($dateOrder){
        /*$order = array(filemtime($filter_files[0]));
        for($i=1; $i<$maxnr+1; $i++){
            array_push($order,filemtime($filter_files[$i]));
        }*/
        $order = array('picture1', 'picture2', 'picture20', 'picture9', 'picture3', 'picture10', 'picture11');
        //array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
        $names = array();
        for($i=0; $i<count($order); $i++) {
            preg_match('/^(.+?)(\d+)$/', $order[$i], $matches);
            $names[] = array($matches[1], $matches[2]);
        }

        $name = array();
        $number = array();
        foreach ($names as $key => $row) {
            $name[$key]  = $row[0];
            $number[$key] = $row[1];
        }
        array_multisort($name, SORT_ASC, $number, SORT_NUMERIC, $names);
        $output = array();
        foreach ($names as $row) {
            $output[] = $row[0] . $row[1];
        }
        print_r($output);
    }

    ?>

Fiddle

相关问题