2012-09-14 38 views
0

我只是在使用php,而且我一直在研究這個代碼效率不高,因爲它很長,我希望它更加自動化。這個想法是生成一個有2個柱子的表格,一個用戶名和另一個用戶的得分。正如您可能想象的那樣,得分基於使用同一用戶的其他變量的函數。我的目標是隻需爲每個用戶設置一個變量,並在表的末尾自動創建一個新行。根據函數創建一個新的數組

<?php 
$array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest 
$array1['BBB'] = "bbb"; ## should be automatic 
$array1['ETC'] = "etc"; 

function getscore($array1){ 
    ## some code 
    return $score; 
    }; 

$score['AAA'] = getscore($array1['AAA']); 
$score['BBB'] = getscore($array1['BBB']); 
$score['ETC'] = getscore($array1['ETC']); 
?> 
<-- Here comes the HTML table ---> 
<html> 
<body> 
<table> 
<thead> 
    <tr> 
     <th>User</th> 
     <th>Score</th> 
    </tr> 
</thead> 
<tbody> 
    <tr> 
     <td>AAA</td> <-- user name should be set automaticlly too --> 
     <td><?php echo $score['AAA'] ?></td> 
    </tr> 
    <tr> 
     <td>BBB</td> 
     <td><?php echo $score['BBB'] ?></td> 
    </tr> 
    <tr> 
     <td>ETC</td> 
     <td><?php echo $winrate['ETC'] ?></td> 
    </tr> 
</tbody> 
</table> 
</body> 
</html> 

任何幫助將受到歡迎!

+0

你的問題到底是什麼?你有什麼嘗試? – jfriend00

+0

有沒有什麼辦法來簡化這段代碼,並根據$ array1的值自動生成行? – mat

+0

這是爲什麼標記[html5]? – PeeHaa

回答

0
$outputHtml = '' 
foreach($array1 as $key => $val) 
{ 
    $outputHtml .= "<tr> "; 
    $outputHtml .= "  <td>$key</td>"; 
    $outputHtml .= "  <td>".getscore($array1[$key]);."</td>"; 
    $outputHtml .= " </tr>"; 
} 

然後$outputHtml將HTML內容包含所有行,你想顯示

0

這是一個少許清潔劑,使用foreachprintf

<?php 

$array1 = array(
    ['AAA'] => "aaa", 
    ['BBB'] => "bbb", 
    ['ETC'] => "etc" 
); 

function getscore($foo) { 
    ## some code 
    $score = rand(1,100); // for example 
    return $score; 
}; 

foreach ($array1 as $key => $value) { 
    $score[$key] = getscore($array1[$key]); 
} 

$fmt='<tr> 
     <td>%s</td> 
     <td>%s</td> 
    </tr>'; 

?> 
<-- Here comes the HTML table ---> 
<html> 
<body> 
<table><thead> 
    <tr> 
     <th>User</th> 
     <th>Score</th> 
    </tr></thead><tbody><?php 

foreach ($array1 as $key => $value) { 
    printf($fmt, $key, $score[$key]); 
} 

?> 
</tbody></table> 
</body> 
</html> 

而且,我就注意到,你似乎沒有在任何地方使用$array1的值。另外, 我不確定$winrate在你的代碼中,所以我忽略了它。

相關問題