使用php读取文件时如何执行某些计算
我用下面的代码扫描了一个目录,工作正常 现在我想得到扫描文件的总数, 所有文件的代码行总数和所有文件的总文件大小,以便保存 目前: 1.)我可以通过下面的代码获得扫描文件的数量使用php读取文件时如何执行某些计算,php,Php,我用下面的代码扫描了一个目录,工作正常 现在我想得到扫描文件的总数, 所有文件的代码行总数和所有文件的总文件大小,以便保存 目前: 1.)我可以通过下面的代码获得扫描文件的数量 $filecount = count(glob($path ."/*")); echo "file count: $filecount"; 2.)我可以通过 $count_line = count(file($file)); $filename_size =filesize($file); 3.)我可以通过 $co
$filecount = count(glob($path ."/*"));
echo "file count: $filecount";
2.)我可以通过
$count_line = count(file($file));
$filename_size =filesize($file);
3.)我可以通过
$count_line = count(file($file));
$filename_size =filesize($file);
我想我必须使用类似于array_sum()的东西,请问我如何得到上面的总和代码>
有人能帮我吗
<?php
function saco($path){
if(file_exists($path) && is_dir($path)){
$files = glob($path ."/*");
// get total number of files
$filecount = count(glob($path ."/*"));
echo "file count: $filecount";
//check if file exist in that directory
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo "$file" . "<br>";
// get line of codes
echo $count_line = count(file($file));
// get filesize of each files
echo $filename_size =filesize($file);
} else if(is_dir("$file")){
// Recursively call the function if directories found
saco("$file");
}
}
}
else{
//echo "ERROR: No such file found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
saco("C:/xampp/htdocs/data");
?>
在循环初始化新变量之前
$count_total=0;
在循环中添加行合计
$count_total += $count_line;
循环结束后,您可以使用$count\u total
echo $count_total;
对大小也做同样的事情。您需要为循环外的每个项目初始化一个计数器,并且由于您是递归计数的,因此您还需要将此计数器保持在函数本身之外,或者将当前进度传递给递归调用
下面是一个将总计存储在全局变量中的示例,全局变量是从函数内部更新的
<?php
$totals = [
'files' => 0,
'lines' => 0,
'size' => 0,
];
function saco($path)
{
global $totals;
if (file_exists($path) && is_dir($path)) {
$files = glob($path . "/*");
// get total number of files
$filecount = count($files);
$totals['files'] += $filecount;
//check if file exist in that directory
if (count($files) > 0) {
// Loop through retuned array
foreach ($files as $file) {
if (is_file("$file")) {
// get line of codes
$count_line = count(file($file));
// get filesize of each files
$filename_size = filesize($file);
$totals['lines'] += $count_line;
$totals['size'] += $filename_size;
} else if (is_dir("$file")) {
// Recursively call the function if directories found
saco($file);
}
}
} else {
//echo "ERROR: No such file found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
saco("C:/xampp/htdocs/data");
$count\u总计+=$count\u行代码>在循环中在循环后回显$count\u total
。sizeshows Undefined变量同上:count\U total您需要在循环$count\U total=0之前对其进行初始化代码>