PHP-scandir()並取得目錄下檔案

scandir 回傳值是Array,回傳值的第一項是「.」,就是目前資料夾的意思,第二項是「..」也就是上一個資料夾,但是沒辦法像glob那樣指定到檔案格式



$arr_Scan = scandir('./');


用scandir()印出結果

Array
(
    [0] => .
    [1] => ..
    [2] => .DS_Store
    [3] => .git
    [4] => FileInc
    [5] => SPD.spd
    [6] => config
    [7] => getFileTicket.php
    [8] => index.php
    [9] => readme.mk
)


列出目錄下檔案

function dirToArray($dir)
{

    $result = array();

    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value, array(".", ".."))) {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
            } else {
                $value = iconv("BIG5", "UTF-8", $value);
                $result[] = $value;
            }
        }
    }

    return $result;
}
可以完整找出資料夾下的所有目錄與檔案.
Array
(
    [0] => .DS_Store
    [.git] => Array
        (
            [0] => COMMIT_EDITMSG
            [1] => HEAD
            [2] => ORIG_HEAD
            [3] => config
            [4] => description
            [hooks] => Array
                (
                    [0] => applypatch-msg.sample
                    [1] => commit-msg.sample
                    [2] => fsmonitor-watchman.sample
                    [3] => post-update.sample
                    [4] => pre-applypatch.sample
                    [5] => pre-commit.sample
                    [6] => pre-push.sample
                    [7] => pre-rebase.sample
                    [8] => pre-receive.sample
                    [9] => prepare-commit-msg.sample
                    [10] => update.sample
                )

            [5] => index
            [info] => Array
                (
                    [0] => exclude
                )

            [logs] => Array
                (
                    [0] => HEAD
                    [refs] => Array
                        (
                            [heads] => Array
                                (
                                    [0] => master
                                )

                        )

                )
...

留言