有没有办法改进以下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';
}
答案 0 :(得分:8)
switch
statement会让你的生活变得更简单。
在这种简单的情况下,这是一个从一个值到另一个值的简单赋值,你也可以使用一个数组:
$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
}
答案 1 :(得分:1)
您可以尝试:
$permission[] = $key == 'insert' ? '1' :
$key == 'inter-insert' ? '2' :
$key == 'intra-insert' ? '3' :
$key == 'view' ? '4' :
// you get the idea...
答案 2 :(得分:1)
你可以使用开关,就像它在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;
}