我正在尝试创建一个函数来检查输入的单词是否已经在我的DB中。
我使用以下代码:
public function contains($string, $pieces)
{
$this->getWords();
$arr = $this->_data; // Get everything from DB
$words = array();
$foundWords = array();
foreach($arr as $key)
{
$words[] = $key->word; // Put words in array
}
foreach($words as $item)
{
if (in_array($item, $words))
{ // Check if entered words are in the DB array
$foundWords[] = $item; // Put already existing words in array
print_r($foundWords);
echo "Match found: ";
echo $item . '<br>'; // Echo found words
return true;
}
echo "Not found!";
return false;
}
}
问题是,它只检查输入单词数组中的第一个单词。有人知道为什么会发生这种事吗?
示例:
用户输入'This is a test'
。DB包含以下单词:This, is, a, test
代码的输出现在应该是Match found: This, is, a, test
,而$foundWords
数组应该包含这些字。
相反,它只找到第一个字,而$foundWords
数组只包含第一个字。因此,Match found: This
。
为函数的返回状态创建一个变量。这里我使用$flag
变量来检查单词的状态。默认情况下,我将变量设置为false,如果找到单词,则从循环中将变量转换为true
和break
,并返回flag
。
public function contains($string, $pieces){
$flag = false;
$this->getWords();
$arr = $this->_data; // Get everything from DB
$words = array();
$foundWords = array();
foreach($arr as $key) {
$words[] = $key->word; // Put words in array
}
foreach($words as $item) {
if (in_array($item, $words)) { // Check if entered words are in the DB array
$foundWords[] = $item; // Put already existing words in array
print_r($foundWords);
echo "Match found: ";
echo $item . '<br>'; // Echo found words
$flag = true; //set true and break from the loop
break;
}else{
echo "Not found!";
$flag = false;
}
}
return $flag;
}
删除"return"并检查是否找到任何单词:
foreach($words as $item) {
if (in_array($item, $words)) { // Check if entered words are in the DB array
$foundWords[] = $item; // Put already existing words in array
}
}
if(count($foundWords) == 0) {
echo "Not found!";
}
else
{
echo "Words: ";
print_r($foundWords);
}