讓我來舉個例子來解釋我期望的。 例如: 我有文件大小「3147483648字節」,我想將它轉換爲以下適當的文件大小: 2 GB + 70 MB + 333 KB + 512字節。php如何將文件大小從字節單位縮小到較大的單位而不用數字舍入
任何幫助表示讚賞。
讓我來舉個例子來解釋我期望的。 例如: 我有文件大小「3147483648字節」,我想將它轉換爲以下適當的文件大小: 2 GB + 70 MB + 333 KB + 512字節。php如何將文件大小從字節單位縮小到較大的單位而不用數字舍入
任何幫助表示讚賞。
我已經找到了解決辦法。我不太喜歡它如何使用遞歸,但它得到我想要的。
function shortenBytes($sizeInBytes){
$units = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB' , 'EB', 'ZB', 'YB');
$resultArray = array(
'YB' => 0,'ZB' => 0,'EB' => 0,'PB' => 0,'TB' => 0,
'GB' => 0,'MB' => 0,'KB' => 0,'Bytes' => 0);
$remainder = $sizeInBytes;
$i = count($units);
while($i >= 0)
{
$pownumber = pow(1024, $i);
if($sizeInBytes >= $pownumber){
$resultArray[$units[$i]] = (int)($sizeInBytes/$pownumber);
$remainder = abs($sizeInBytes % $pownumber);
$i--;
$remainder = recursiveGetUnitArray($remainder,$i,$resultArray);
}
$sizeInBytes = $remainder;
$i--;
}
return $resultArray;
}
function recursiveGetUnitArray($sizeInBytes, $i, &$resultArray){
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB' , 'EB', 'ZB', 'YB');
$remainder = $sizeInBytes;
$pownumber = pow(1024, $i);
if($sizeInBytes >= $pownumber){
$resultArray[$units[$i]] = (int)($sizeInBytes/$pownumber);
$remainder = abs($sizeInBytes % $pownumber);
$i--;
$remainder = recursiveGetUnitArray($remainder,$i,$resultArray);
}
return $remainder;
}
的shortenBytes(3147483648);
array (size=9)
'YB' => int 0
'ZB' => int 0
'EB' => int 0
'PB' => int 0
'TB' => int 0
'GB' => int 2
'MB' => int 70
'KB' => int 333
'Bytes' => int 512
您可以編寫自己的函數,該函數: 喜歡的東西
bytes = filesize % 1024;
filesize = (int)(filesize/1024);
kbytes = filesize % 1024;
filesize = (int)(filesize/1024);
等等...
我已經搜索了很多代碼,並且從字節到所有特定大單元都有,但沒有我想要的是。 在你的回答中,爲什麼我必須再次將文件大小分爲1024?我認爲它應該從單元的頂端計算,但不是從字節到更高單元。 – 2013-03-27 09:54:31
參見官方網站php.net結果:
<?php
function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1)/3);
return sprintf("%.{$decimals}f", $bytes/pow(1024, $factor)) . @$sz[$factor];
}
?>
它被提及[轉換字節到千兆字節](http://stackoverflow.com/questions/2510434/php-format-bytes-to-kilobytes-megabytes-gigabytes),它不是我的問題。 – 2013-03-27 11:21:38
這是相同的轉換秒至例如天數/小時/分/秒。嘗試使用Google搜索。 – Jon 2013-03-27 09:05:17
'kb = floor(bytes/1024)',然後從原來的'bytes- = kb'中刪除它並重復更大的面值 – Waygood 2013-03-27 09:06:47