php递归获取目录名和子文件名

php递归获取目录名和子文件名

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
//递归获取所有文件和文件夹
function get_dirs($dir_path) {
    $res = array();
    $res_lists = array();

    foreach(glob("$dir_path/*") as $item) {
        if(is_dir($item)) {
            $folder = end(explode('/', $item));
            $res[$folder] =get_dirs($item);
            continue;
        }
        $res[] = basename($item);
    }    
    return $res    ;   
}
echo "<pre>";
print_r ( get_dirs( dirname(__FILE__)."/md-file") );
echo "</pre>";

Array ( [0-index] => Array ( [0] => Hans.md )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[1-tds] => Array
    (
    )

[77-list1] => Array
    (
        [1-list2] => Array
            (
                [1-list3] => Array
                    (
                    )

            )

    )

[88-robotnote] => Array
    (
        [0] => Hans.md
    )

[99-contact] => Array
    (
        [0] => Hans.md
        [1] => Hant.md
        [2] => en.md
    )

)

1
只要文件夹

//递归获取 只要文件夹 function get_dirs($dir_path) { $res = array(); $res_lists = array();

1
2
3
4
5
6
7
8
9
foreach(glob("$dir_path/*") as $item) {
    if(is_dir($item)) {
        $folder = end(explode('/', $item));
        $res[$folder] =get_dirs($item);
        continue;
    }
    
}    
return $res    ;   

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Array
(
    [0-index] => Array
        (
        )

    [1-tds] => Array
        (
        )

    [77-list1] => Array
        (
            [1-list2] => Array
                (
                    [1-list3] => Array
                        (
                        )

                )

        )

    [88-robotnote] => Array
        (
        )

    [99-contact] => Array
        (
        )

)
```
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus