0

我有一个 PHP 数组

$array = array(
           "PHP server side scripting",
           "CSE for designing",
           "Client side scripting JavaScript, HTML etc",
           "Java object oriented programming"
         }

和一个数据库表

+-------+-----------------+
|  id   | language        |
+-------+-----------------+
|   1   | PHP             |
|   2   | JavaScript      |
|   3   | CSE             |
|   4   | C++             |
+-------+-----------------+

如何使用查询将数组项与数据库表的字段部分匹配。

必需的输出仅与 PHP 数组匹配的语言

+-------+-----------------+
|  id   | language        |
+-------+-----------------+
|   1   | PHP             |
|   2   | JavaScript      |
|   3   | CSE             |
+-------+-----------------+

我尝试了以下但没有得到实际结果。

foreach($array as $val) {
    $sql = "SELECT * FROM my_table WHERE language LIKE '%$val%'";
    //remaining code
}    

提前致谢。

4

1 回答 1

0

从 db 获取所有语言然后检查数组中的语言会更容易。

如果您想在查询中进行查询,则必须执行以下操作:

$array = array(
    "PHP server side scripting",
    "CSE for designing",
    "Client side scripting JavaScript, HTML etc",
    "Java object oriented programming"
);

foreach($array as $val) {
    $valArray = explode(" ", $val);
    $where = "";
    foreach ($valArray as $word) {
        $word = trim($word, ",.");
        if ($where) {
            $where .= " OR ";
        }
        $where .= " language LIKE '%$word%' ";
    }
    $sql = "SELECT * FROM my_table WHERE $where";
    //remaining code
} 

但这是丑陋的解决方案

于 2013-11-01T17:12:56.237 回答