dqy006150 2018-11-25 10:50
浏览 95
已采纳

在一个函数中声明的数组(在嵌套函数中填充)保持空白

I've written the below function, but fileList is blank when echoed out. Any ideas why this might be happening? and how to fix it?

function testing($dir){
echo $dir;
$fileList=array();

    function recursiveScan($dir) {

        $tree = glob(rtrim($dir, '/') . '/*');
        if (is_array($tree)) {
            foreach($tree as $file) {
                if (is_dir($file)) {
                    echo $file . '('.filemtime($file).')'.'<br/>';
                    recursiveScan($file);
                    $fileList[date('YmdHis',filemtime($file))]=$file;
                } elseif (is_file($file)) {
                    echo $file . '('.filemtime($file).')'.'<br/>';
                    $fileList[date('YmdHis',filemtime($file))]=$file;

                }
            }
        ?>
<pre>
<?php print_r($fileList);?>
</pre>
<?php   

        }

    }
}

EDIT:

If I move the print_r bit of the code below up a few } then it outputs... but I want to output it once all directories have been searched through.

function recursiveScan($dir) {

        $tree = glob(rtrim($dir, '/') . '/*');
        if (is_array($tree)) {
            foreach($tree as $file) {
                if (is_dir($file)) {
                    echo $file . '('.filemtime($file).')'.'<br/>';
                    recursiveScan($file);
                    $fileList[date('YmdHis',filemtime($file))]=$file;
                } elseif (is_file($file)) {
                    echo $file . '('.filemtime($file).')'.'<br/>';
                    $fileList[date('YmdHis',filemtime($file))]=$file;

                }
            }
        }
    ?>
    <pre>
    <?php print_r($fileList);?>
    </pre>
    <?php

}
  • 写回答

1条回答 默认 最新

  • dongxi1879 2018-11-25 12:47
    关注

    I think better approach will be to use the return value to function argument to get the results. Consider the following function:

    function recursiveScan($dir, $fileList) {
            $tree = glob(rtrim($dir, '/') . '/*');
            if (is_array($tree)) {
                foreach($tree as $file) {
                    if (is_dir($file)) {
                        $fileList = recursiveScan($file, $fileList);
                    } elseif (is_file($file)) {
                        $fileList[date('YmdHis',filemtime($file))]=$file;
                    }
                }
            }
            return $fileList;
    }
    

    Now you can trigger the first call by doing something like:

    $dir = "/"; // or from argument
    $fileList = recursiveScan($dir, array());
    

    After that, the $fileList will contain list of the files

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?