我有兩個字串,我需要比較每個句子的單詞。字串是這兩個:
$correctSentence = "The year stations are summer, winter, spring and fall."
$textSentence = "The year stations are four summer, winter and spring and summer."
所以,我為每個句子制作陣列,然后我有下一個陣列來比較句子之間不相似的單詞。
$correctArray = ["The", "year", "stations", "are", "summer", "winter", "spring", "and", "fall"];
$textArray = ["The", "year", "stations", "are", "four", "summer", "winter", "and", "spring", "and", "summer"];
我正在以這種形式比較陣列:使用 for 回圈,我將 $textArray 的每個單詞與 $correctArray 的單詞進行比較。如果 $textArray[$i] 的單詞與 $correctArray 的任何單詞都不相似,則該單詞將存盤在一個名為 $finalArray 的新陣列中
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
}
}
$finalArray 的結果是這樣的:
$finalArray = ["four", "winter"];
但我還需要在 $finalArray 中存盤在 $textArray 中重復的單詞,如下所示:
$finalArray = ["four", "winter", "and", "summer"];
因為“and”和“summer”在$textSentence和$textArray中是重復的,所以單詞與$correctSentence和$correctArray的單詞不相似
我認為解決方案是在本節中 if 條件為真時洗掉 $correctArray 的類似詞:
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
//In this section, delete the word of $correctArray
//which is similar of $textArray[$i].
//For example: After comparing "summer" of $textArray[$i] with "summer" of $correctArray.
//The record "summer" of $correctArray should be deleted.
//And this way the following record "summer" of $textArray (which is duplicated)
//should be stored in $finalArray
}
}
但我不知道該怎么做。有人可以幫我嗎
uj5u.com熱心網友回復:
您可以計算出現在$textArrayusing中的回圈字串/單詞array_count_values(),并檢查計數值是否大于 1(表示重復)而不是 insert into $finalArray,也可能在插入之前$finalArray您需要檢查字串/單詞是否已存在于內部$finalArray。
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
}
// count how many times the string appear in the array
$total_string_in_array = array_count_values($textArray)[$textArray[$i]];
if ($total_string_in_array > 1) {
// check if the duplicate string already exists inside $finalArray
if ( ! in_array($textArray[$i], $finalArray)) {
array_push($finalArray, $textArray[$i]);
}
}
}
參考:
- array_count_values():https ://www.php.net/manual/en/function.array-count-values.php
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514902.html
下一篇:如何對匯編中的兩個陣列元素求和?
