使用循环 If、Elseif 和 Else 从数据库中查找字符 Stripost

Find Characters Stripost From Database Using Loop If, Elseif and Else

我有以下代码:

for ($y = 0; $y <= $count_1; $y++) {
    for ($x = 0; $x <= $count_2; $x++) {
        if((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],$search_quest[$x])!==false) and (stripos($answ[$y],$search_answ[$x])!== false)) { 
            $ai_cat_detail ="FOUND";
        } else {
            $ai_cat_detail ="N/A";
        }
    }
    echo $ai_cat_detail."<br>";
}

结果是:

N/A
N/A
N/A
N/A
N/A

我的期望值是这样的:
找到
找到
找到
N/A
N/A

并使用此代码成功:

if((strpos($cat[$y],"Model 1")!==false)and(stripos($quest[$y],"Search Quest 1")!==false) and (stripos($answ[$y],"Search Answer 1")!== false)) {     
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and(stripos($quest[$y],"Search Quest 2")!==false) and (stripos($answ[$y],"Search Answer 2")!== false)){ 
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],"Search Quest 3")!==false) and (stripos($answ[$y],"Search Answer 3")!== false)) { 
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],"Search Quest 4")!==false) and (stripos($answ[$y],"Search Answer 4")!== false)) { 
    $ai_cat_detail = "FOUND";
} else { 
    $ai_cat_detail = "N/A";
}

那么我能做些什么来循环 else if 并以 else 代码结束,就像我上面的成功代码一样?

感谢帮助

你在循环中覆盖 $ai_cat_detail 的值时输出错误 - 所以最后一个赋值是 N/A 是你回显的那个(所以它会回显 FOUND仅当找到最后一个 if 时。

为了修复将检查导出到函数和 return 字符串值或使用 break 作为:

for ($y = 0; $y <= $count_1; $y++) {
    for ($x = 0; $x <= $count_2; $x++) {
        if((strpos($cat[$y],"Model 1") !== false) and (stripos($quest[$y],$search_quest[$x]) !== false) and (stripos($answ[$y],$search_answ[$x]) !== false)) { 
            $ai_cat_detail ="FOUND";
            break; // this will stop the loop if founded
        } else {
            $ai_cat_detail ="N/A";
        }
    }
    echo $ai_cat_detail."<br>";
}

或使用如下函数:

function existIn($cat, $search_quest, $search_answ, $count_2, $y) {
    for ($x = 0; $x <= $count_2; $x++) {
        if((strpos($cat[$y],"Model 1") !== false) and (stripos($quest[$y],$search_quest[$x]) !== false) and (stripos($answ[$y],$search_answ[$x]) !== false)) { 
            return "FOUND";
        }
    }
    return "N/A";

//use as
for ($y = 0; $y <= $count_1; $y++) {
    echo existIn($cat, $search_quest, $search_answ, $count_2, $y) ."<br>";
}