2016-05-05 39 views
1

我想創建一個函數,檢查輸入的單詞是否已經在我的數據庫中。in_array方法只運行一次?

我使用以下代碼:

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

+2

你知道什麼'return'確實在函數/方法,不是嗎? –

+1

您需要在此處使用'break'語句並在函數的最後一行返回您的值。 –

+0

@MarkBaker感謝您通知我。我完全忘了它停止了這個功能。這解決了它! – Chris

回答

1

從函數中爲返回狀態創建一個變量。在這裏,我使用$flag變量來檢查單詞的狀態。默認情況下,我將變量設置爲false,並且如果找到該單詞,則將該變量從循環變爲truebreak,並返回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; 
} 
0

刪除「收益」和檢查,如果你發現任何文字畢竟:

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); 
    }