2012-09-14 39 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在你的代码中,所以我忽略了它。

相关问题