-2

我正在尝试将此字节转换为图像主机的千兆字节,请帮助并感谢您,抱歉英语不好:

function foldersize($dir){
 $count_size = 0;
 $count = 0;
 $dir_array = scandir($dir);
 foreach($dir_array as $key=>$filename){
  if($filename!=".." && $filename!="."){
   if(is_dir($dir."/".$filename)){
    $new_foldersize = foldersize($dir."/".$filename);
    $count_size = $count_size + $new_foldersize[0];
    $count = $count + $new_foldersize[1];
   }else if(is_file($dir."/".$filename)){
    $count_size = $count_size + filesize($dir."/".$filename);
    $count++;
   }
  }

 }

 return array($count_size,$count);
}

$sample = foldersize("images");

echo "" . $sample[1] . " images hosted " ;
echo "" . $sample[0] . " total space used </br>" ;
4

4 回答 4

5
echo "" . $sample[0]/(1024*1024*1024) . " total space used </br>" ;
于 2013-05-16T01:06:09.920 回答
1

我个人更喜欢一种简单而优雅的解决方案:

function formatSize($bytes,$decimals=2){
    $size=array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
    $factor=floor((strlen($bytes)-1)/3);
    return sprintf("%.{$decimals}f",$bytes/pow(1024,$factor)).@$size[$factor];
}
于 2018-02-26T03:45:18.893 回答
0

这应该会自动确定最佳单位。如果您愿意,我可以向您展示如何强制它始终使用 GB。

将此添加到您的代码中:

$units = explode(' ', 'B KB MB GB TB PB');

function format_size($size) {
    global $units;

    $mod = 1024;

    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }

    $endIndex = strpos($size, ".")+3;

    return substr( $size, 0, $endIndex).' '.$units[$i];
}

测试它:

echo "" . $sample[1] . " images hosted " ;
echo "" . format_size($sample[0]) . " total space used </br>" 

来源:https ://stackoverflow.com/a/8348396/1136832

于 2013-05-16T01:12:34.977 回答
0
function convertFromBytes($bytes)
{
    $bytes /= 1024;
    if ($bytes >= 1024 * 1024) {
        $bytes /= 1024;
        return number_format($bytes / 1024, 1) . ' GB';
    } elseif($bytes >= 1024 && $bytes < 1024 * 1024) {
        return number_format($bytes / 1024, 1) . ' MB';
    } else {
        return number_format($bytes, 1) . ' KB';
    }
}
于 2019-02-05T17:23:04.613 回答