2012-09-14 4 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> 

도움이 될 것입니다! $outputHtml에서 다음

+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>"; 
} 

모든 행 네가 원하는 디스플레이

0

foreachprintf 사용하여 약간의 청소기와 HTML 내용이 될 것입니다, 또한

<?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이 무엇인지 확실하지 않으므로 무시했습니다.

관련 문제