1

我目前正在手动编写 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;
    }

如何使这个 if 语句自动递增$user_location[]and$page[]而不是手动编码?

4

5 回答 5

0

你能翻转数组然后直接搜索吗?

$flipped = array_flip($user_location);
$user_id = isset($flipped[$location]) ? $page[$flipped[$location]] : $user_gen;

如果数组被翻转,您可以看到键$location代表什么并将其用作 $page 上的索引。如果未设置,它将默认为 $user_gen 如上所述。

于 2013-08-29T13:28:58.960 回答
0

最简单的解决方案可能是使用foreach

$user_id = $user_gen;
foreach($user_location as $key => $ulocation) {
    if ($ulocation == $location) {
        $user_id = $page[$key];
        break;
    }
}
于 2013-08-29T13:15:10.153 回答
0

你能试试这个吗?

$user_id = $user_gen;
foreach($user_location as $key => $value){
    if($value == $location){
        $user_id = $page[$key];
        $location_find = true;
    }
}
于 2013-08-29T13:15:36.793 回答
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;
}
于 2013-08-29T13:18:29.183 回答
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];
}
于 2013-08-29T13:52:15.757 回答