我正在一个项目中尝试在用户提交时从帖子中获取主题标签。然后,将火柴放入数据库中以供参考。我的问题是,有没有更有效的方法?我当前的代码运行方式太多,导致发布时间缓慢。
该代码循环遍历每个标签,并检查它是否存在于数据库中(如果存在),只是添加一个引用该标签的项目(如果不存在),则将其添加到数据库中,并添加标签的引用和发布。
我尝试了这个,但不知道在哪里可以用相同的功能进行改进
foreach($hashtags as $tag){
if(DB::query('SELECT * FROM tags WHERE tag=:tag', array(':tag' => $tag))){
$tag = DB::query('SELECT * FROM tags WHERE tag=:tag', array(':tag' => $tag))[0];
DB::query ( "INSERT INTO post_tags VALUES(:tagid, :postid)", array (':tagid' => $tag['id'], ':postid' => $postid) );
}else{
$id = hash(sha256, $tag);
DB::query ( "INSERT INTO tags VALUES(:id, :tag, :mode)", array (':id' => $id, ':tag' => $tag, ':mode' => 0) );
DB::query ( "INSERT INTO post_tags VALUES(:tagid, :postid)", array (':tagid' => $id, ':postid' => $postid) );
}
}
最佳答案
不要在查询中直接比较您的标签。我建议获取数组中的所有标签,然后使用in_array
函数进行检查。会更快。
如果要进行查询比较,请在标签列中添加索引,这样可以使您的比较更快。
说明:(简要)
通过查询表将所有标签放入php数组。为此,查询应没有任何条件,例如
$tag = DB::query('SELECT * FROM tags')[0];
如果不是,则将查询结果转换为数组并将其存储到同一数组中,例如
$tag = $tag->toArray();
然后遍历输入数组标记以检查它们是否存在:
$filteredArray = array();
$newTags = array();
foreach($hashtags as $t) {
if(in_array($t, $tag))
{
$filteredArray[] = $t;
}
else {
$newTags[] = $t;
}
}
然后使用插入查询将匹配的标签插入数据库。
if(!empty($allTags)) {
$allTags = array_column($t,'id');
DB::query ( "INSERT INTO post_tags VALUES(:tagid, :postid)", array (':tagid' => $allTags, ':postid' => $postid) );
}
else
{
// Otherwise get all the new tags and then insert them along with mode = 0 and create `post_tags` too.
}
注意:这是一个完全简短的想法。您应纠正条件并正确设置。
关于php - 遍历字符串中的主题标签并插入数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50036646/