有時候我們需要在網頁上顯示某個檔案的大小,或是其它資料的大小數字。
這個數字往往從跨度很大,如果以B為單位的話可能是個位,如果1G則長達1073741824的數字,這個時候我們就需要根據大小來格式化,比如小於1K則以B為單位顯示,小於1M則以KB為單位顯示,小於1G則以MB為單位顯示,以此類推...
格式化函數參考如下:
<span>//</span><span>格式化size显示</span> <span>function</span> formatSize(<span>$b</span>,<span>$times</span>=0<span>){ </span> <span>if</span>(<span>$b</span>>1024<span>){ </span><span>$temp</span>=<span>$b</span>/1024<span>; </span><span>return</span> formatSize(<span>$temp</span>,<span>$times</span>+1<span>); }</span><span>else</span><span>{ </span><span>$unit</span>='B'<span>; </span><span>switch</span>(<span>$times</span><span>){ </span><span>case</span> '0':<span>$unit</span>='B';<span>break</span><span>; </span><span>case</span> '1':<span>$unit</span>='KB';<span>break</span><span>; </span><span>case</span> '2':<span>$unit</span>='MB';<span>break</span><span>; </span><span>case</span> '3':<span>$unit</span>='GB';<span>break</span><span>; </span><span>case</span> '4':<span>$unit</span>='TB';<span>break</span><span>; </span><span>case</span> '5':<span>$unit</span>='PB';<span>break</span><span>; </span><span>case</span> '6':<span>$unit</span>='EB';<span>break</span><span>; </span><span>case</span> '7':<span>$unit</span>='ZB';<span>break</span><span>; </span><span>default</span>: <span>$unit</span>='单位未知'<span>; } </span><span>return</span> <span>sprintf</span>('%.2f',<span>$b</span>).<span>$unit</span><span>; } }</span>
呼叫:
<span>echo</span> formatSize('20667564');
結果是:
19.71MB
說明:
其中參數$b是以B為單位的數字,$times是用來識別這個函數遞歸了多少次的。
其中不常用的單位TB、PB、EB、ZB請參考下面的備註(來源於網路):
1bit(這個位元表示一個二進位數字)1Byte(這個單字音譯過來也叫「位元」但是表示一個十六進位數字)
1B=1Byte=8bit
1 kB = 1024 B (kB - kilobyte)千
1 MB = 1024 kB (MB - megabyte) 兆
1 GB = 1024 MB (GB - gigabyte) 吉
1 TB = 1024 GB (TB - terabyte) 太
1 PB = 1024 GB (TB - TBBte) 太
1 PB = 1024 TB ( 1 EB = 1024 PB (EB - eksabyte) 艾
1 ZB = 1024 EB (ZB - zettabyte) 皆
1 YB = 1024 ZB (YB - yottabyte) 佑
1 BB = 1024 YB (YB - yottabyte) 佑
1 BB = 1024 YB (YB - BBy) [它], Y. 10^21,
zetta, 澤[它], Z. 10^18,
exa, 艾[可薩], E. 10^15,
peta, 拍[它], P. 10 ^12,
tera, 太[拉], T. 10^9,
giga, 吉[咖], G. 10^6,
mega, 兆,M. 10^3
以上就介紹了PHP格式化(檔案)儲存資料大小(SIZE)顯示,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。