2015-07-10 57 views
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

$forceFormatfalse$suffixtrue。我不明白它爲什麼會返回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

$bytes0時,表達$bytes >= 1073741824 && $forceFormat === false評估爲falseswitch聲明跳轉到表達式匹配$bytes的第一個case。以下腳本演示,false匹配0

<?php  
switch (0) { 
    case false: 
    echo '0 is false'; 
    break; 
    case true: 
    echo '0 is true'; 
    break; 
    default: 
    echo '0 is something else'; 
    break; 
} 
?> 

因爲要跳到第一個case這是true你應該使用switch (true)

+0

啊我明白了。是的,不幸的是,這聽起來非常合乎邏輯。沒想到這一點。有什麼辦法可以避免這種情況,並將0作爲數字處理? – SheperdOfFire

+0

正如我上面提到的,你只需要將'switch($ bytes)'改成'switch(true)'就可以使你的代碼工作。 – just95

+0

啊,現在我明白了。所以實際上一個switch語句是沒有用的。 – SheperdOfFire