gpt4 book ai didi

php - 在循环外创建查询

转载 作者:行者123 更新时间:2023-11-28 23:17:24 25 4
gpt4 key购买 nike

我正在尝试检查字典中是否存在大句子(10k 或更多单词)中的单词,但是多次执行我的查询会使我的页面变慢。如何将查询移出循环以加快页面速度?

foreach ($word as $key => $value) {
$checkWord = checkDict($value);
if($checkWord==true){
return $value;
} else {
$word[$key] = Del_Inflection_Suffixes($value); //skip this function
if(checkWord($value)){
return $value;
}
$word[$key] = Del_Derivation_Suffixes($value); //skip this function
if(checkWord($value)){
return $value;
}
$word[$key] = Del_Derivation_Prefix($value); //skip this function
if(checkWord($value)){
return $value;
}
}
}

function checkDict($rootWord){ //check if the word already exist in the database
$sql = mysql_query("SELECT * from dictionary where rootword ='$rootWord' LIMIT 1");
$result = mysql_num_rows($sql);
if($result==1){
return true;
}else{
return false;
}
}

最佳答案

您的脚本之所以如此缓慢,是因为通常执行数千个数据库查询将成为一个巨大的瓶颈。因此,您应该重新考虑您的逻辑。我还假设您将放弃 mysql_* 函数,因为它们不应该被使用。我在回答中使用了 PDO。

1。选择整个表格:

选择整个表,将其放入数组中并使用 PHP 检查该词是否存在。

$stmt = $dbh->query("SELECT rootword from dictionary");
$dictionary = $stmt->fetchAll();

foreach ($word as $key => $value) {
if (in_array($value, $dictionary)) {
// word exists
}
else {
// word doesn't exist
}
}

2。使用 IN

根据您的表的大小,上述方法也可能不会非常有效,并且您甚至可能会耗尽内存,具体取决于您的 PHP 设置。因此,您可以将所有单词添加到 MySQL 中的 IN() 中。请注意还有一个 limit to the amount you can pass to IN

$in  = str_repeat('?,', count($word) - 1) . '?';
$stmt = $db->prepare("SELECT rootword FROM dictionary WHERE rootword IN ($in)");
$stmt->execute($word);
$dictionary = $stmt->fetchAll();

foreach ($word as $key => $value) {
if (in_array($value, $dictionary)) {
// word exists
}
else {
// word doesn't exist
}
}

关于php - 在循环外创建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263881/

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