PHP数组项与数据库表部分匹配

时间:2013-11-01 16:57:27

标签: php mysql arrays

我有一个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
}    

提前致谢。

1 个答案:

答案 0 :(得分: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
} 

但那是丑陋的解决方案