gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:06:03 25 4
gpt4 key购买 nike

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

提前致谢。

最佳答案

从数据库获取所有语言然后检查数组中有哪些语言会更容易。

如果您想在查询中使用它,那么您必须执行以下操作:

$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
}

但这是一个丑陋的解决方案

关于PHP 数组项与数据库表部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19731474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com