Php 基于函数创建新数组
我只是在学习使用php,我一直在编写这段代码,但效率不高,因为它很长,我希望它能更自动化。其思想是生成一个包含2列的表,一列包含用户名,另一列包含每个用户的分数。正如您所想象的,分数基于使用同一用户的其他变量的函数。我的目标是只需要为每个用户设置一个变量,并在表的末尾自动创建一个新行Php 基于函数创建新数组,php,html,Php,Html,我只是在学习使用php,我一直在编写这段代码,但效率不高,因为它很长,我希望它能更自动化。其思想是生成一个包含2列的表,一列包含用户名,另一列包含每个用户的分数。正如您所想象的,分数基于使用同一用户的其他变量的函数。我的目标是只需要为每个用户设置一个变量,并在表的末尾自动创建一个新行 <?php $array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest $array1['BBB']
<?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=''
foreach($array1作为$key=>$val)
{
$outputHtml.=”;
$outputHtml.=“$key”;
$outputHtml.=''.getscore($array1[$key]);.'';
$outputHtml.=”;
}
然后在$outputHtml
中将是html内容,其中包含所有要显示的行使用foreach
和printf
,这会稍微干净一些:
<?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
,所以我忽略了它。您的问题到底是什么?您尝试了什么?是否有任何方法可以简化此代码并根据$array1的值自动生成行?
<?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>