2016-07-07 24 views
1

方面PHP disk_total_space()的輸出我從我的項目這個代碼片斷那裏得到的自由空間在我指定的磁盤所以這裏是隱蔽的在GB

$ds = disk_total_space(substr(base_path(), 0, 2)); 
$fs = disk_free_space(substr(base_path(), 0, 2)); 

所以我需要做的它始終以GB的形式返回任何想法,我可以做到這一點?非常感謝!

更新 我發現這個代碼,它覆羽字節爲不同格式的

if ($ds >= 1073741824) 
    { 
     $ds = number_format($ds/1073741824, 2) . ' GB'; 
    } 
    elseif ($ds >= 1048576) 
    { 
     $ds = number_format($ds/1048576, 2) . ' MB'; 
    } 
    elseif ($ds >= 1024) 
    { 
     $ds = number_format($ds/1024, 2) . ' KB'; 
    } 
    elseif ($ds > 1) 
    { 
     $ds = $ds . ' B'; 
    } 
    elseif ($ds == 1) 
    { 
     $ds = $ds . ' B'; 
    } 
    else 
    { 
     $ds = '0 size'; 
    } 

如何,我只能使它成爲唯一GB什麼想法?

回答

1

我用這個功能:)

private function convGB($bytes, $unit = "", $decimals = 2) 
{ 
    $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
    'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8); 

    $value = 0; 
    if ($bytes > 0) 
    { 
     if (!array_key_exists($unit, $units)) 
     { 
      $pow = floor(log($bytes)/log(1024)); 
      $unit = array_search($pow, $units); 
     } 

     $value = ($bytes/pow(1024,floor($units[$unit]))); 
    } 

    if (!is_numeric($decimals) || $decimals < 0) { 
    $decimals = 2; 
    } 

    return sprintf('%.' . $decimals . 'f '.$unit, $value); 
} 

調用它像convGB(*bytes in here*);