2016-04-21 27 views
-2

我正在使用用户可以上传文件的文件夹。这些文件与名称和大小一起输出。如何在foreach循环中创建文件时统计文件大小

$dir = "users/$UserName"; 
$files = scandir($dir); 

foreach ($files as $file) { 
if ($file != '.' && $file != '..') { 
echo sizeFormat(filesize($dir . '/' . $file)); 
} 

所以我的输出是这样的:

koala.jpg => 600KB

jellyfish.jpg => 600KB

tulips.jpg => 500KB

哪有我计算所有的大小在一起?

喜欢的东西:特里大小的所有文件:1700kB

回答

1

像这样:

$dir = "users/$UserName"; 
$files = scandir($dir); 
$total = 0; 

foreach ($files as $file) { 
    if ($file != '.' && $file != '..') { 
     $total += filesize($dir . '/' . $file); 
     echo sizeFormat(filesize($dir . '/' . $file)); 
    } 
} 
echo $total; 
+0

的伟大工程!谢谢 –

0

呃... ...刚才添加的尺寸一起!?

假设你的代码的作品,这里是一个样机如何做到这一点:

$total = 0; 
foreach ($files as $file) { 
    if ($file != '.' && $file != '..') { 
     $current = filesize($dir . '/' . $file); 
     $total += $current; 
     echo sizeFormat($current); 
    } 
} 
echo "total: ".sizeFormat($total); 
0

试试这个(假设你有地方的sizeFormat功能)

$dir = "users/$UserName"; 
$files = scandir($dir); 
$size = 0; 

foreach ($files as $file) { 
    if ($file != '.' && $file != '..') { 
     $size += filesize($dir . '/' . $file); 
    } 
} 

echo sizeFormat($size);