[英]How I can simplify this PHP code? too many switch() function
我在 jQuery Mobile 中创建了列表视图,并使用 PHP 来提供其内容。 它工作正常,但代码太长,其中大部分内容彼此非常相似。 有什么办法可以简化代码吗? 请看一下代码,然后我将解释我真正需要做什么:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
switch ($row[1]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
// second column check
switch ($row[2]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// third column check
switch ($row[3]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fourth column check
switch ($row[4]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fifth column check
switch ($row[5]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// sixth column check
switch ($row[6]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
default:
echo " N ";
}
echo "</li></a>";
}
?>
</a></li>
</ol>
结果是:
通过使用while ($row = mysql_fetch_array($result)){
我可以一一获取sql表的每一行。 但我还需要检查每个单元格(列)的值。
将代码分组为一个 2 参数函数:
function checkRowValue($row, $checkDefault) {
switch ($row) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
if ($checkDefault)
echo " N . ";
}
}
调用为:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
for ($i = 0; $i < 7; $i++)
checkRowValue($row[i], $i > 0);
}
这通过在行中的所有列上应用一个函数(首先跳过)然后将它们用" . "
串在一起来概括它。
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<li><a href=\"#\">";
echo join(' . ', array_map(function($v) {
if ($v == 'Behnam') {
return 'B';
elseif ($v == 'Tarin') {
return 'T';
else {
return 'N';
}
}, array_slice($row, 1));
echo "</li></a>";
}
尝试这个
if(in_array("Behnam",$row) {
echo " B . ";
}
else if(in_array("Train",$row) {
echo " T . ";
}
else {
echo " N . ";
}
这是最终结果:
<ul id="competition_list" data-role="listview" data-inset="true" data-theme="a">
<?php
// using the returned value from database to feed the list.
// showing the competiton rounds' outcome.
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
echo $row[0] . "."; //this is the id column in the table and will give me the number of the row
for($i = 1; $i <= 5; $i++){
switch ($row[$i]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
}
} // end for()
echo "</a></li>";
} // end while()
?>
</ul>
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
foreach($row as r)
{
switch (r) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.