0

100 個のレコードを表示する mySQL を介して単純なクエリ システムを作成し、それらをゲームにフェッチしましたが、PHP のコードに問題があります。

各行の間に 5 文字のスペースが必要なので、タブ スペース ( \t\t\t\t\t)を使用する必要があります。異なる結果が得られます:

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

2 に答える 2

1

Tab in fact is one char, but displayed in the way that user want. When, for example, in IDE you choose 8 spaces for 1 tab you will get it. There's a fantastic concept called elastic tabstops, but it's only concept - so sad.

Conclusion: you can't do it what you described with tab.

What you can do:

  • Calculate needed spaces and hardcode with &nbsp;, but it's dirty and you shouldn't do this.
  • Use html tables
于 2012-06-03T20:41:10.087 に答える
1

$row['...'] の代わりに sprintf("%-15s", $row['...']) を使用しますが、それぞれの場所で数値 (-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));
}
于 2012-06-03T20:45:35.107 に答える