如何在PHP中简化多个开关?

时间:2013-08-15 19:13:40

标签: php while-loop switch-statement

是否可以简化此代码?我试图将所有情况都放在一个开关中,但总是在第一种情况下中断,我需要在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;
}

2 个答案:

答案 0 :(得分: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>";
    }
}

[edit]我看到我们有了一些新变量。

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

答案 1 :(得分:0)

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

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