有没有人知道如何将可能是byte,kb,mb,gb等的类型转换为另一种类型,例如我有以下
ini_get('upload_max_filesize')
//这可能是mb我此刻的值是64m因此我需要补偿较短的缩写
和mb中的值我需要将其转换为kb或任何其他类型
Helper::convertType(ini_get('upload_max_filesize'), 'kb'); the kb coulb be bytes or gb
答案 0 :(得分:1)
您可以使用此代码作为帮助程序,使其具有人类可读性:
/** * Converts bytes into human readable file size. * * @param string $bytes * @return string human readable file size (2,87 Мб) * @author Mogilev Arseny */ function FileSizeConvert($bytes) { $bytes = floatval($bytes); $arBytes = array( 0 => array( "UNIT" => "TB", "VALUE" => pow(1024, 4) ), 1 => array( "UNIT" => "GB", "VALUE" => pow(1024, 3) ), 2 => array( "UNIT" => "MB", "VALUE" => pow(1024, 2) ), 3 => array( "UNIT" => "KB", "VALUE" => 1024 ), 4 => array( "UNIT" => "B", "VALUE" => 1 ), ); foreach($arBytes as $arItem) { if($bytes >= $arItem["VALUE"]) { $result = $bytes / $arItem["VALUE"]; $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; break; } } return $result; }
或使用此功能手动转换文件大小:
function changeType($size, $from, $to){ $arr = ['B', 'KB', 'MB', 'GB', 'TB']; $tSayi = array_search($to, $arr); $eSayi = array_search($from, $arr); $pow = $eSayi - $tSayi; return $size * pow(1024, $pow) . ' ' . $to; } echo changeType(1, 'MB', 'KB');