1
我有這個功能不起作用:文件大小轉換字節到KB/MB/GB功能如預期
function formatSizeUnits($bytes,array $options = array()){
$forceFormat = isset($options["forceFormat"]) ? $options["forceFormat"] : false;
$suffix = !isset($options["suffix"]) || $options["suffix"] === true ? true : false;
switch($bytes):
case $forceFormat === "gb":
case $bytes >= 1073741824 && $forceFormat === false:
$bytes = number_format($bytes/1073741824, 2) . ($suffix === true ? " GB" : "");
break;
case $forceFormat === "mb":
case $bytes >= 1048576 && $forceFormat === false:
$bytes = number_format($bytes/1048576, 2) . ($suffix === true ? " MB" : "");
break;
case $forceFormat === "kb":
case $bytes >= 1024 && $forceFormat === false:
$bytes = number_format($bytes/1024, 2) . ($suffix === true ? " KB" : "");
break;
case $forceFormat === "b":
case $bytes > 1 && $forceFormat === false:
$bytes = $bytes . ($suffix === true ? " bytes" : "");
break;
case $bytes == 1 && $forceFormat === false:
$bytes = $bytes . ($suffix === true ? " byte" : "");
break;
default:
$bytes = "0".($suffix === true ? " bytes" : "");
endswitch;
return $bytes;
}
當我運行它像這樣:
formatSizeUnits(0);
它返回: 0.00 GB
$forceFormat
是false
和$suffix
是true
。我不明白它爲什麼會返回GB
。我希望它只返回0 bytes
。
當我在第一個switch語句(的gb
一)把var_dump
它這樣說:
case $forceFormat === "gb":
case $bytes >= 1073741824 && $forceFormat === false:
var_dump($bytes >= 1073741824, $forceFormat);
結果:
(bool(false)
bool(false)
我不知道爲什麼都$bytes >= 1073741824
和$forceFormat
能是假的,它仍然運行這種情況。 我該如何解決這個問題?
啊我明白了。是的,不幸的是,這聽起來非常合乎邏輯。沒想到這一點。有什麼辦法可以避免這種情況,並將0作爲數字處理? – SheperdOfFire
正如我上面提到的,你只需要將'switch($ bytes)'改成'switch(true)'就可以使你的代碼工作。 – just95
啊,現在我明白了。所以實際上一個switch語句是沒有用的。 – SheperdOfFire