我目前正在编写我的if else语句
if ($user_location[0] == $location){
$user_id = $page[0];
} else if ($user_location[1] == $location){
$user_id = $page[1];
} else if ($user_location[2] == $location){
$user_id = $page[2];
} else if ($user_location[3] == $location){
$user_id = $page[3];
} else if ($user_location[4] == $location){
$user_id = $page[4];
} else if ($user_location[5] == $location){
$user_id = $page[5];
} else if ($user_location[6] == $location){
$user_id = $page[6];
} else if ($user_location[7] == $location){
$user_id = $page[7];
} else if ($user_location[8] == $location){
$user_id = $page[8];
} else {
$user_id = $user_gen;
}
如何创建自动增加$user_location[]
和$page[]
而不是手动编码的if语句?
答案 0 :(得分:0)
最简单的解决方案可能是使用foreach
:
$user_id = $user_gen;
foreach($user_location as $key => $ulocation) {
if ($ulocation == $location) {
$user_id = $page[$key];
break;
}
}
答案 1 :(得分:0)
你能试试吗?
$user_id = $user_gen;
foreach($user_location as $key => $value){
if($value == $location){
$user_id = $page[$key];
$location_find = true;
}
}
答案 2 :(得分:0)
试试这个:
我假设您正在使用PHP,因为您在PHP中标记了您的问题
$flag = true;
foreach($user_location as $index=>$each){
if ($each == $location){
$flag = false;
$user_id = $page[$index];
}
}
if ($flag){
$user_id = $user_gen;
}
答案 3 :(得分:0)
你可以翻转阵列然后直接搜索吗?
$flipped = array_flip($user_location);
$user_id = isset($flipped[$location]) ? $page[$flipped[$location]] : $user_gen;
如果数组被翻转,您可以看到键$location
代表什么,并将其用作$ page上的索引。如果没有设置,它将默认为$ user_gen,如上所述。
答案 4 :(得分:0)
我会使用array_search:
$user_id = $user_gen;
$user_id_index = array_search($location, $user_location);
if (false !== $user_id_index) {
$user_id = $page[$user_id_index];
}