0

是否可以简化此代码?我试图将所有情况都放在一个开关中,但在第一种情况下总是会中断,我需要 html 中的所有回显。什么是可能的?谢谢!

$resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = $id_client");

while($rowservice = mysqli_fetch_array($resultservices)){
    $php = (int)$rowservice['php'];
    $java = (int)$rowservice['java'];
    $ruby = (int)$rowservice['ruby'];
    $node = (int)$rowservice['node'];
}

// Values can be "1" or "0". Example: php:1, java:1, ruby:0, node:1

switch ($php) {
    case 0: break;
    case 1: echo "<li>php</li>"; break;
}

switch ($java) {
    case 0: break;
    case 1: echo "<li>java</li>"; break;
}

switch ($ruby) {
    case 0: break;
    case 1: echo "<li>ruby</li>"; break;
}

switch ($node) {
    case 0: break;
    case 1: echo "<li>node</li>"; break;
}
4

2 回答 2

4

虽然我不确定您要做什么,但如何:

$resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = $id_client");

while($rowservice = mysqli_fetch_array($resultservices)){
    $service[1] = (int)$rowservice['1'];
    $service[2] = (int)$rowservice['1'];
    $service[3] = (int)$rowservice['0'];
    $service[4] = (int)$rowservice['1'];
}

foreach ($service as $k=>$v) {
    if ($v) {
        echo "<li>service".$k."</li>";
    }
}

[编辑] 我看到我们有一些新变量。

while($rowservice = mysqli_fetch_array($resultservices)){
    $service['php'] = (int)$rowservice['php'];
    $service['java'] = (int)$rowservice['java'];
    $service['ruby'] = (int)$rowservice['ruby'];
    $service['node'] = (int)$rowservice['node'];
}

foreach ($service as $k=>$v) {
    if ($v) {
        echo "<li>".$k."</li>";
    }
}

虽然实际上,您所做的只是输出 MySQL 的最后一行,所以您也可以这样做

    $resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = '".mysqli_real_escape_string($connecDB, $id_client)."' ORDER BY id DESC LIMIT 1");

    while($rowservice = mysqli_fetch_array($resultservices)){
        if ($rowservice['php']) {
            echo "<li>php</li>"
        }
        if ($rowservice['java']) {
            echo "<li>java</li>"
        }
        if ($rowservice['ruby']) {
            echo "<li>ruby</li>"
        }
        if ($rowservice['node']) {
            echo "<li>node</li>"
        }
    }
于 2013-08-15T19:16:32.053 回答
0

鉴于您的四个服务值中有 3 个将具有相同的值,您可以消除 2 个开关并最终得到相同的结果:

$service01 = (int)$rowservice['1'];
$service02 = (int)$rowservice['1']; // identical to service01
$service03 = (int)$rowservice['0'];
$service04 = (int)$rowservice['1']; // identical to service01

意味着你可以拥有:

switch($service01) {
    case 0: break;
    case 1: echo "<li>service01, 02, and 04</li>"; break;
}

然后,假设这些值永远不会是真/假 0/1 值,您可以完全消除开关并使用传统的if

if ($service01) {
    echo "service 01, 02 and 04";
}
于 2013-08-15T19:22:30.303 回答