gpt4 book ai didi

php - MySql:类似子句中匹配的无序单词

转载 作者:行者123 更新时间:2023-11-29 13:19:18 24 4
gpt4 key购买 nike

如何实现名称匹配。像“John S Smith”这样的东西必须与 mysql 数据库中的“Smith John S”相匹配。即单词可以是无序的。

是否可以在单个 SQL 查询中完成此操作?因为是名字,所以不会超过3个字。

我的代码逻辑上不正确。任何帮助将不胜感激。

$words=explode(" ", $name);

$sql="SELECT * FROM sent WHERE 1=1";

foreach ($words as $word)
{
$sql.=" AND customer_name LIKE '%$word%'";
}

我得到的结果 SQL 看起来像这样。

$sql="SELECT * FROM sent WHERE 1=1 AND customer_name LIKE '%John%' AND customer_name LIKE '%S%' AND customer_name LIKE '%Smith%'" ;

最佳答案

下面的代码将首先找到所有可能的单词组合,然后将其与数据库进行匹配由于您的代码最多只有 3 个单词,因此这不是一个坏选择

    <?php
$name ='John S Smith';
$words=explode(" ", $name);;

function get_all_combination($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;

for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
get_all_combination($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}

$collect = array();
get_all_combination($words, "", $collect);

/*
$collect now have

[0] => John
[1] => John S
[2] => John S Smith
[3] => John Smith
[4] => John Smith S
[5] => S
[6] => S John
[7] => S John Smith
[8] => S Smith
[9] => S Smith John
[10] => Smith
[11] => Smith John
[12] => Smith John S
[13] => Smith S
[14] => Smith S John
*/

$sql="SELECT * FROM sent WHERE 1=1 AND (customer_name = '".implode("' OR customer_name = '",$collect)."')" ;




?>

关于php - MySql:类似子句中匹配的无序单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063704/

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