我有一个页面,它从数据库中获取信息并将其显示在表格中。它确实有效,但它非常麻烦。
//Table header here
echo "<tr><td>".$teamname."</td>";
//For Gameweek 7
if ($gw7 == "")
{
//The team has no game - highlight the cell in red
echo "<td align='center' style='background: #FF0000'>";
}
elseif (strpos($gw7,'/') !== false)
{
//The team has 2 games this week - highlight it in green
echo "<td align='center' style='background: #00FF00'>";
}
else
{
//this means the team has a single game this week - normal cell.
echo "<td align='center'>";
}
echo $gw7."</td>";
echo "</tr>";
//for gameweek 8 to 36, the above for loop is just repeated (mostly copy/pasted)
//Table footer here
有更干净的方法吗?我不喜欢多次复制/粘贴相同的代码。
游戏周被称为$gw7
,$gw8
,$gw9
,$gw10
等,并包含团队面对的文本格式的对手。 $ gw7中的7个代表本赛季的第7场比赛。他们被分为游戏周。如果不清楚,请告诉我。
答案 0 :(得分:1)
像这样创建函数
function gw($week) {
//For Gameweek 7
if ($week == "")
{
//The team has no game - highlight the cell in red
echo "<td align='center' style='background: #FF0000'>";
}
elseif (strpos($week,'/') !== false)
{
//The team has 2 games this week - highlight it in green
echo "<td align='center' style='background: #00FF00'>";
}
else
{
//this means the team has a single game this week - normal cell.
echo "<td align='center'>";
}
echo $week."</td>";
}
//Table header here
echo "<tr><td>".$teamname."</td>";
gw($gw7); // call here function for $gw7 for others as well
echo "</tr>";
答案 1 :(得分:1)
$team_array=array("team1","team2","team3","team4"); //as many teams you want
foreach($team_array as $teamname)
{
$rows=getfixturesfromdb($teamname);
//if fixtures are like $rows['gw1'],$rows['gw2']....etc
foreach($row as $gw)
{
echo "<tr><td>".$teamname."</td>";
if ($gw == "")
{
//The team has no game - highlight the cell in red
echo "<td align='center' style='background: #FF0000'>";
}
elseif (strpos($gw,'/') !== false)
{
//The team has 2 games this week - highlight it in green
echo "<td align='center' style='background: #00FF00'>";
}
else
{
//this means the team has a single game this week - normal cell.
echo "<td align='center'>";
}
echo $gw."</td>";
echo "</tr>";
}
}
答案 2 :(得分:0)
你把游戏周刊放在一个数组中,遍历并调用6以上数组索引的自定义代码。
function table_cell($color) {
echo "<td align='center' style='background: $color'>";
}
//Table header here
echo "<tr><td>".$teamname."</td>";
//For Gameweek 7
if ($gw7 == "")
{
table_cell('#FF0000');
//The team has no game - highlight the cell in red
}
elseif (strpos($gw7,'/') !== false)
{
table_cell('#00FF00');
//The team has 2 games this week - highlight it in green
}
else
{
//this means the team has a single game this week - normal cell.
echo "<td align='center'>";
}
echo $gw7."</td>";
echo "</tr>";