How to recursively iterate through files in PHP?

后端 未结 7 1830
走了就别回头了
走了就别回头了 2021-02-12 16:47

I have set up a basic script that is posting an array of paths to find template files inside them; currently it\'s only searching two levels deep and I\'m having some troubles g

7条回答
  •  日久生厌
    2021-02-12 17:10

    Universal File search in folder, sub-folder :

    function dirToArray($dir,$file_name) {
       $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,$file_name);
             }
             else
             {
                if($value == $file_name){
                    $result[] = $value; 
                }
             }
          }
       }
       return $result;
    }
    
    define('ROOT', dirname(__FILE__));
    $file_name = 'template.html';
    $tree = dirToArray(ROOT,$file_name);
    echo "
    ".print_r($tree,1)."
    ";

    OUTPUT :

    Array
    (
        [components] => Array
            (
                [side] => Array
                    (
                        [second] => Array
                            (
                                [0] => template.html
                                [third] => Array
                                    (
                                        [0] => template.html
                                    )
    
                            )
    
                        [0] => template.html
                    )
    
                [0] => template.html
            )
    
        [0] => template.html
    )
    

提交回复
热议问题