0

我创建了一个函数来计算和显示目录中的文件数,但它不起作用。

功能 :

<?php
function nnndir($dirx)
{
    $direx=opendir("$dirx");

    $nfiles=0;

    while($filexx=readdir($direx))
    {
        if ($filexx!="." && $filexx!=".." && $filexx!="config.dat")
        {
            $nfiles++;
        }
    }

    closedir($direx);

    $num_f="Number of Files it´s : ".$nfiles."";

    global $num_f;
}

nnndir("".$ruta_path_adm."".$ruta_db."/db_register");

echo $num_f;
?>

应该显示数字,但通常不会。但是,它似乎间歇性地工作。我该如何纠正?

4

2 回答 2

3

When a function terminates, all its local variables disappear. $num_f disappears after }, global shouldn't be used for that. You should use a return value :

<?php
function nnndir($dirx)
{
    $direx=opendir("$dirx");
    $nfiles=0;

    while($filexx=readdir($direx))
    {
        if ($filexx!="." && $filexx!=".." && $filexx!="config.dat") $nfiles++;
    }

    closedir($direx);
    return $nfiles;
}

echo "Number of files : " . nndir("".$ruta_path_adm."".$ruta_db."/db_register");
?>

By the way, you don't need to write this function :

$number_of_files = count(scandir("".$ruta_path_adm."".$ruta_db."/db_register")) - 2;

scandir returns an array containing the content of a directory. I use count() to get the number of elements, and substract 2 for . and ...

于 2013-07-14T19:42:11.437 回答
0
<¿php
    function count_files($dir)
    {
        $files = scandir($dir);
        return count($files) - 2; // We remove 2, "." and ".." occurences
    }

    $num_files = count_files("".$ruta_path_adm."".$ruta_db."/db_register");
    echo "Number of files: {$num_files}";

    // For having an array of filenames, just call:
    // $filesArray = scandir("".$ruta_path_adm."".$ruta_db."/db_register");
?>

更好的方法(避免调用 scandir() 两次)是分析目录并一次返回所有数据的函数。

<¿php
    function analyze_dir($dir)
    {
        $ret = array();
        $ret['filelist'] = scandir($dir);
        $ret['num_files'] = count($ret['filelist']) - 2; // We remove 2, "." and ".." occurences
        return $ret;
    }

    $data = analyze_dir("".$ruta_path_adm."".$ruta_db."/db_register");
    echo "Number of files: {$data['num_files']}";

    // The array of filenames is $data['filelist']
?>
于 2013-07-14T19:54:43.787 回答