php - PHP:有条件插入
问题描述
我有一个这样的查询:
$content = "How technology is helping to change the way people think about the food on their plate and the food impact for them. Technology could have a role to play in raising awareness of the impact our diets have on the planet.";
$exp = explode(" ", $content)
for($j = 0; $j < count($exp); $j++){
$this->db->query("INSERT INTO news (news_id, news_content) VALUES ('$id', $exp[$j])");
}
但是,我不想插入所有的词,我只需要插入只出现多次的词(技术、食物、影响)。有可能这样做吗?有人能帮我吗?
解决方案
我将处理文本内容array_filter
以排除停用词列表中的单词,然后计算每个单词的出现次数,然后计算array_count_values
出array_filter
只出现一次的单词。然后,您可以将剩余的单词(将是输出数组的键)写入数据库。例如:
$content = "How technology is helping to change the way people think about the food on their plate and the food impact for them. Technology could have a role to play in raising awareness of the impact our diets have on the planet.";
$stopwords = array('how', 'is', 'to', 'the', 'way', 'on', 'and', 'for', 'a', 'in', 'of', 'our', 'have');
// count all words in $content not in the stopwords list
$counts = array_count_values(array_filter(explode(' ', strtolower($content)), function ($w) use ($stopwords) {
return !in_array($w, $stopwords);
}));
// filter out words only seen once
$counts = array_filter($counts, function ($v) { return $v > 1; });
// write those words to the database
foreach ($counts as $key => $value) {
$this->db->query("INSERT INTO news (news_id, news_content) VALUES ('$id', '$key')");
}
对于您的样本数据,最终结果$counts
将是:
Array
(
[technology] => 2
[food] => 2
[impact] => 2
)
推荐阅读
- java - 使用不需要的值在 Java 中执行两次(错误)的查询
- jquery - 在 RabbitMQ 上升级到 JQuery 版本 3.5.0 或更高版本
- java - 尝试将环境变量读取到自定义属性文件中,而不是在 spring boot 中的 application.property
- ios - Xcode if 语句从不识别活动编译条件
- android - Flutter AppUpdateService 链接到死亡
- python - 如果元素不存在,则使用 getElementsByTagName 跳过元素
- css - 使用滑块 Angular 平滑颜色变化
- python - Google Drive API Quickstart.py 错误 400:redirect_uri_mismatch
- reactjs - 如何在反应打字稿的导航栏中创建动态元素
- python-3.x - Poppler pdftohtml.exe 无法通过 IIS7 加载