0

有没有办法改进以下if语句块?我只是想知道是否有人可以使这段代码更简单、更干净。

if($key == 'insert'){
    $permission[] = '1';
}else if($key == 'inter-insert'){
    $permission[] = '2';
}else if($key == 'intra-insert'){
    $permission[] = '3';
}else if($key == 'view'){
    $permission[] = '4';
}else if($key == 'inter-view'){
    $permission[] = '5';
}else if($key == 'intra-view'){
    $permission[] = '6';
}else if($key == 'update'){
    $permission[] = '7';
}else if($key == 'inter-update'){
    $permission[] = '8';
}else if($key == 'intra-update'){
    $permission[] = '9';
}else if($key == 'delete'){
    $permission[] = '10';
}else if($key == 'inter-delete'){
    $permission[] = '11';
}else if($key == 'intra-delete'){
    $permission[] = '12';
}
4

3 回答 3

8

一个switch声明会让你的生活更简单一些。

然而,在这种简单的情况下,它是从一个值到另一个值的简单赋值,您也可以使用数组:

$permissions = array(
 "insert" =>       "1", 
 "intra-insert" => "2",
 "inter-insert" => "3",
 // etc.
);

isset($permissions[$key]) && $permission[] = $permissions[$key];

或另一种变体:

$keyExists = array_key_exists($key, $permissions);
if ($keyExists) {
    $permission[] = $permissions[$key];
} else {
    echo "Key not found!"; // or whatever   
}
于 2012-06-16T12:32:54.147 回答
1

你可以试试:

$permission[] = $key == 'insert' ? '1' :
                $key == 'inter-insert' ? '2' :
                $key == 'intra-insert' ? '3' : 
                $key == 'view' ? '4' :
                // you get the idea...
于 2012-06-16T12:33:24.977 回答
1

你可以使用 switch,就像在 C 中一样:

switch ($i) {
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
default: break;
}
于 2012-06-16T12:35:24.370 回答