我正在用PHP构建用户模块。它读取基于文本的用户类型,并分配一个数值来管理报表视图权限:
if ($usr_type == "Architect"){ $usr_rights = 0; }
if ($usr_type == "Director"){ $usr_rights = 1; }
if ($usr_type == "Manager"){ $usr_rights = 2; }
if ($usr_type == "Associate"){ $usr_rights = 3; }
if ($usr_type == "Assistant"){ $usr_rights = 4; }
if ($usr_type == "External"){ $usr_rights = 5; }
有更简单,更优雅的方法吗?
答案 0 :(得分:5)
您可以使用switch()
执行if工作。
switch($usr_type) {
case "Architect":
$usr_rights = 0;
break;
case "Director":
$usr_rights = 1;
break;
case "Manager":
$usr_rights = 2;
break;
case "Associate":
$usr_rights = 3;
break;
case "Assistant":
$usr_rights = 4;
break;
case "External":
$usr_rights = 5;
break;
}
或使用数组。
$valid_types = array(
"Architect" => 0,
"Director" => 1,
"Manager" => 2,
"Associate" => 3,
"Assistant" => 4,
"External" => 5
);
if(isset($valid_types[$usr_type])) {
$usr_rights = $valid_types[$usr_type];
}
答案 1 :(得分:3)
我从你当前的解决方案中看到了两种不同的解决方案。
1。像这样制作一个开关语句:
switch($usr_type) {
case "Architect":
$usr_rights = 0;
break;
case "Director":
$usr_rights = 1;
break;
//...
}
有关switch()
的详情,请参阅手册:http://php.net/manual/en/control-structures.switch.php
2。或者制作一个数组并在其中搜索:
$arr = array(0 => "Architect", 1 => "Director", 2 => "Manager", 3 => "Associate", 4 => "Assistant", 5 => "External");
if(array_search($usr_type, $arr) !== false)
$usr_rights = array_search($usr_type, $arr);
答案 2 :(得分:1)
您需要使用switch statement
switch($usr_type) {
case "Architect":
$usr_rights = 0;
break;
case "Director":
$usr_rights = 1;
break;
case "Manager":
$usr_rights = 2;
etc..
}
答案 3 :(得分:0)
您可以使用数组函数array_map
。如果我们考虑" Architect"," Director"等是关键。然后我们可以使用地图结构来组合键及其值。
<?php
$usr_rights = array(0, 1, 2, 3, 4, 5);
$usr_types = array("Architect", "Director", "Manager", "Associate", "Assistant","External");
$c = array_combine($usr_types,$usr_rights);
print_r($d);
// Test
echo $c["Architect"]; // output: 0
?>