从FTP阵列返回的PHP阵列排序列表

时间:2019-06-08 10:06:10

标签: php arrays sorting

我从ftp服务器以数组形式返回了文件:

Array
(
    [0] => FOLDER./Images.Vacation.2018
    [1] => ./Images.Vacation.2018/Racoon001.jpg
    [2] => ./Images.Vacation.2018/Racoon002.txt
    [3] => ./Images.Vacation.2018/the.racoon.swimming.mp4
    [4] => ./Images.Vacation.2018/the.racoon.swimming.slv
    [5] => FOLDER./WestImages
    [6] => ./WestImages/Ramco.txt
    [7] => ./WestImages/Ramco.jpg
    [8] => FOLDER./WestImages/Subimages
    [9] => ./WestImages/Subimages/Image001.jpg
    [10] => ./WestImages/Subimages/Image002.jpg
    [11] => ./WestImages/West.Ramco.Swimming.mp4
)

您可以看到SubImages在WestImages之前返回,这是错误的...所以我无法使用和

  • 标记在我的文件夹中显示正确的文件...我需要数组来返回此:

    Array
    (
        [0] => FOLDER./Images.Vacation.2018
        [1] => ./Images.Vacation.2018/Racoon001.jpg
        [2] => ./Images.Vacation.2018/Racoon002.txt
        [3] => ./Images.Vacation.2018/the.racoon.swimming.mp4
        [4] => ./Images.Vacation.2018/the.racoon.swimming.slv
        [5] => FOLDER./WestImages
        [6] => ./WestImages/Ramco.txt
        [7] => ./WestImages/Ramco.jpg
        [8] => ./WestImages/West.Ramco.Swimming.mp4
        [9] => FOLDER./WestImages/Subimages
        [10] => ./WestImages/Subimages/Image001.jpg
        [11] => ./WestImages/Subimages/Image002.jpg
    )
    

    这是我的ftp代码,可从服务器读取文件:

    /* contents - ftp function */
        function ftp_list_files_recursive($ftp_stream, $path){
            $lines = ftp_rawlist($ftp_stream, $path);
    
            $result = array();
    
            foreach ($lines as $line){
                $tokens = explode(" ", $line);
                $name = $tokens[count($tokens) - 1];
                $type = $tokens[0][0];
                $filepath = $path . "/" . $name;
    
                if ($type == 'd'){
                    $result[] = 'FOLDER'.$filepath;
                    $result = array_merge($result, ftp_list_files_recursive($ftp_stream, $filepath));
                } elseif ($type == '-'){
                    $result[] = $filepath;
                }
            }
            return $result;
        }
    
        /* contents - ftp */
        $contents = ftp_list_files_recursive($conn_id, ".");
    
        echo '<pre>';
        print_r($contents);
        echo '</pre>';
    

    我尝试使用sort($contents);但是它给我返回了错误的排序...如何重写函数以返回正确的排序,如上面给出的?

    谢谢。

  • 1 个答案:

    答案 0 :(得分:1)

    这不是一个很好的解决方案,但是您可以使用preg_grep获取文件夹名称,然后将其循环并grep文件。

    $folders = preg_grep("/^FOLDER.*/", $arr);
    
    foreach($folders as $folder){
        $result[] = $folder;
        $result = array_merge($result, preg_grep("/^\." . str_replace(["FOLDER.", "/"], ["","\/"], $folder) . "\/[A-Za-z0-9\.]+$/", $arr));
    }
    
    var_dump($result);
    

    https://3v4l.org/BthA0