【发布时间】:2019-05-19 00:29:09
【问题描述】:
我一直在努力使以下代码更有效率。
总之;
我有一个包含标题和描述的数据库。该数据库将平均 10000 条文本。我想通过使用“mb_split”拆分文本来搜索比较这些文本,然后遍历所有其他文本以比较该词是否存在。根据进行的比较次数,我想将文章编号写入该数据库中的另一个表。
下面的代码可以工作并且可以解决问题,但是需要很长时间才能完成并使用大量资源。我似乎找不到更有效地比较这些文本的方法。
function compareArticle() {
include '../include/write.php';
$readNewsQuery = "select title,text,articleid,name from texts";
$readNews = $dbwrite->query($readNewsQuery);
if ($readNews) {
//Fetch mysql data as an array
$news = $readNews->fetch_all(MYSQLI_NUM);
// Start foreach to read every article once
foreach ($news as $item) {
echo $item[2].'<br />';
// Start another foreach to loop through the articles to compare with
foreach ($news as $compare) {
$strippedWords = mb_split(' +', $item[0]);
$count = 0;
$compareString = "";
$compareString .= $compare[0];
$compareString .= $compare[1];
$compareString = strtolower($compareString);
// Start yet another foreach to loop through the words
foreach ($strippedWords as $word) {
// I only want to count the words that are longer than 4 characters
if (strlen($word) > 4) {
$woord = strtolower($word);
if (strpos($compareString, $word) && $compare[2] != $item[2]) {
$count++;
}
}
}
if ($count > 5) {
echo $count.'<br />';
//Insert action to write comparison to database (item[2] and compare[2])
}
}
}
}
}
我真正想知道的;我可以更有效率吗?我可以使用更少的循环,还是有更简单的方法来搜索数组?如果我可以更有效率,有人可以在正确的方向上推动我吗?
编辑: 了解我检索到的数据以及我想写入另一个表的数据可能很有用:
texts-database 设置为包含
| article id | title | text | sourcename
我将标题中的单词与所有其他文章的标题和文本组合的单词进行比较。如果它们足够匹配,我想将两个文章 id 写入另一个表:
| id | original article id | compared article id |
【问题讨论】:
-
在sql中直接使用
LIKE或REGEXP。 -
是的,有趣的注释@DavidLemon,我刚开始只是使用 MySQL 来收集大部分数据,而且这似乎要快得多。它与我的 cronjobs 结合导致了一些问题,我希望 PHP 数组比我在 MySQL 上拍摄的 mysql 查询更快。结果并非如此。我会考虑你的建议,因为我 100% 确信我可以使用一些更高级的 MySQL 查询来提高我的脚本的效率。
标签: php performance mysqli foreach strpos