2012-06-03 71 views
0

我通過mySQL製作了一個簡單的查詢系統,它向我展示了100條記錄,並將它們提取到我的遊戲中,但我用PHP中的代碼獲得了probelm。我想要使​​用標籤空間(\t\t\t\t\t),但我有這個當前系統的問題(例如,如果我有字段與兩個不同的字符串值10char和2char然後使用選項卡空間,使它們之間的空間,我得到不同的結果:標籤空間問題

2Char string + 5char space = 7Char10Char string + 5Char space = 15Char

$query = "SELECT * FROM `scores` ORDER by `score` DESC LIMIT 100"; 
$result = mysql_query($query) or die('Query failed: ' . mysql_error()); 

$num_results = mysql_num_rows($result); 

for($i = 0; $i < $num_results; $i++) 
{ 
    $row = mysql_fetch_array($result); 
    echo $i+1 . "-" . "\t\t Name: " .$row['name'] . "\t\t\t\t Device: " . $row['device'] . "\n \t\t Difficulty: " . $row['level']. "\t\t\t\t Score: " . $row['score'] . "\n\n"; 
} 

代碼輸出

1- Name: James Device: HTC OneX 
    Difficulty: Hard Score: 5760 

2- Name: Erika_S  Device: PC 
    Difficulty: Normal  Score: 13780 

... 

我所需的輸出

1- Name: James   Device: HTC OneX 
    Difficulty: Hard  Score: 5760 

2- Name: Erika_S  Device: PC 
    Difficulty: Normal Score: 13780 
... 
+4

您不應該使用製表符,因爲它們的實際寬度_widely vary_。如果這是一個瀏覽器,你有沒有考慮過使用HTML表格? – Litty

+0

如果您仍然需要使用製表符,請務必在決定要顯示多少製表符之前對文本進行計數。也就是說,如果你不知道製表符將使用多大的尺寸(空間),有時候用空格會更好。我還假設你使用的是等寬字體... – Christian

+1

你知道 和str_repeat嗎? – Oliver

回答

1

其實Tab是一個字符,但在用戶希望的方式顯示。例如,當您在IDE中爲1個選項卡選擇8個空格時,您將獲得它。有一個夢幻般的概念叫做elastic tabstops,但它只是概念 - 非常難過。

結論:你不能這樣做,你用tab描述。

你可以做什麼:

  • 計算所需的空間,並與&nbsp;硬編碼,但它是骯髒的,你不應該這樣做。
  • 使用HTML表格
+0

謝謝,但我不能使用html表格。 – iSun

1

,而不是$行[ '... ']用sprintf( 「% - 15」,$行[' ...']),但在每一個地方,你會需要調整到什麼是真正需要的數量(-15)

<?php 
$s = 'monkey'; 
$t = 'many monkeys'; 

printf("[%s]\n",  $s); // standard string output 
printf("[%10s]\n", $s); // right-justification with spaces 
printf("[%-10s]\n", $s); // left-justification with spaces 
printf("[%010s]\n", $s); // zero-padding works on strings too 
printf("[%'#10s]\n", $s); // use the custom padding character '#' 
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters 
?> 
The above example will output: 
[monkey] 
[ monkey] 
[monkey ] 
[0000monkey] 
[####monkey] 
[many monke] 

閱讀更多http://www.php.net/manual/en/function.sprintf.php

,如果你不能用printf,你可以輕鬆地創建自己的函數,它類似的東西,並且是足以滿足您的需求:

function add_spaces($str, $total_len) { 
    return $str . substr("       ", 0, $total_len - strlen($str)); 
} 
+0

謝謝,但是當我使用printf(...);我的遊戲引擎返回錯誤,但它通常在瀏覽器中正常工作。 – iSun

+3

好吧,讀你的心思會返回一個錯誤,但是如果你能發佈錯誤信息我們可能會幫到:) – Gavriel

+0

也是我的錯,試試用sprintf代替printf – Gavriel