首页 > 解决方案 > 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])");
}

但是,我不想插入所有的词,我只需要插入只出现多次的词(技术、食物、影响)。有可能这样做吗?有人能帮我吗?

标签: phpmysql

解决方案


我将处理文本内容array_filter以排除停用词列表中的单词,然后计算每个单词的出现次数,然后计算array_count_valuesarray_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
)

推荐阅读