以GB为单位转换php disk_total_space()的输出
我从我的项目中得到了这个代码片段,它在我指定的磁盘中获得了可用空间,所以它就在这里以GB为单位转换php disk_total_space()的输出,php,Php,我从我的项目中得到了这个代码片段,它在我指定的磁盘中获得了可用空间,所以它就在这里 $ds = disk_total_space(substr(base_path(), 0, 2)); $fs = disk_free_space(substr(base_path(), 0, 2)); 因此,我需要做的是始终以GB为单位返回值。关于我如何能做到这一点,有什么想法吗?非常感谢 更新 我发现这段代码将字节转换成不同的格式 if ($ds >= 1073741824) {
$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吗 我使用了这个函数:)
私有函数convGB($bytes,$unit=“”,$decimals=2)
{
$units=数组('B'=>0,'KB'=>1,'MB'=>2,'GB'=>3,'TB'=>4,
‘PB’=>5,‘EB’=>6,‘ZB’=>7,‘YB’=>8);
$value=0;
如果($bytes>0)
{
如果(!array_key_存在($unit,$units))
{
$pow=floor(log($bytes)/log(1024));
$unit=数组搜索($pow,$units);
}
$value=($bytes/pow(1024,floor($units[$unit]));
}
如果(!is_numeric($decimals)| |$decimals<0){
$decimals=2;
}
返回sprintf('%..$decimals.'f'.$unit,$value);
}
像convGB(*此处为字节*)一样调用它代码>
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);
}