如何转动递归函数opendir

时间:2014-06-27 17:49:09

标签: php recursion opendir

您想要转换下面的递归函数吗? 但保留允许的文件扩展名(xml)的过滤器。

function lista_xml($path) {
 $xml_array = Array(); 
    $dh = opendir($path); 
      while ( false !== ($file = readdir($dh)) )
    {
        if ( $file=="." || $file==".." || is_dir($file) ) continue; 
        $namearr = explode('.',$file);
        if ($namearr[count($namearr)-1] == 'xml') $xml_array[] = $file; 
    } 
    closedir($dh);
    return $xml_array;
}

My Folder:
Path/directory1/aaa.xml;bbb.xml;
Path/directory1/directory2/xxx.xml;yyy.xml;
Path/directory1/directory2/directory3/ccc.xml;

I want a unique array:
[0] => aaa.xml
[1] => bbb.xml
[2] => xxx.xml
[3] => yyy.xml
[4] => ccc.xml

1 个答案:

答案 0 :(得分:0)

使return变量也是一个输入变量,并在子目录上递归调用它自己。

function lista_xml($path, $xml_array=array()) {
    $dh = opendir($path); 
    while ( false !== ($file = readdir($dh)) )
    {
        if ($file == '.' || $file == '..') continue;
        $file = realpath($path . '/' .basename($file));

        $info = pathinfo($file);
        if (isset($info['extension']) && $info['extension'] == 'xml') {
            $xml_array[] = $file;
        } elseif ( $file!='.' && $file!='..' && is_dir($file)) {
            $xml_array = lista_xml($file, $xml_array);
        }
    } 
    closedir($dh);
    return $xml_array;
}