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

时间:2019-02-14 03:10:16

标签: php arrays loops stripos

我有以下代码:

INFO: Versions: lxml 4.2.5.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.9.0, Python 3.7.0 (default, Oct  9 2018, 10:31:47) - [GCC 7.3.0], pyOpenSSL 18.0.0 (OpenSSL 1.0.2p  14 Aug 2018), cryptography 2.3.1, Platform Linux-4.14.97-90.72.amzn2.x86_64-x86_64-with-glibc2.9

结果是:

不适用
不适用
不适用
不适用
N / A

我期望这样的值:
找到
找到
找到
不适用
N / A

并成功使用此代码:

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>";
}

如果要循环其他代码,并以其他代码结束,例如上面的成功代码,我该怎么办?

感谢帮助

1 个答案:

答案 0 :(得分:0)

您在覆盖循环中的$ai_cat_detail的值时有错误的输出-因此最后一个赋值是N/A是您要回显的值(因此只有在以下情况下才会回显FOUND找到最后一个。

为了解决该问题,将检查功能导出并返回字符串值或使用 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>";
}