我正在尝试根据文章包含的团队将我的文章与不同的团队联系起来。目前我有以下 3 个表:
teams(id, name, shortname)
news(id, title, text, url)
contain(team_id, news_id)
我的问题是在执行插入查询之后
mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')");
我想检查变量 $full_text_strip 是否包含团队名称或短名称之一,如果是,它应该使用刚刚创建的 news_id 和 team_id 在包含表中创建一个新记录。最简单的方法是什么?
最佳答案
这是一个未经测试的 SQL 解决方案:
<?php
$query = "select name, shortname, id from teams";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$ids[$row['id'][] = $row['name'];
$ids[$row['id']][] = $row['shortname'];
}
foreach($ids as $id => $teams) {
foreach($teams as $team) {
if(strpos($full_text_strip, $team) !== false) {
//mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')");
echo 'We are inserting here because ' . $team . ' is present.';
}
}
}
?>
测试代码:
<?php
$title = 'this is input blue jays for the testing';
$ids = array(1 => array('blue jay', 'blues'), 2 => array('red sox', 'reds'), 3 => array('white sox', 'whites'));
foreach($ids as $id => $teams) {
foreach($teams as $team) {
if(strpos($title, $team) !== false) {
echo 'Insert ' . $team . 'with id ' . $id;
}
}
}
关于php - 检查文章是否包含团队名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461694/