2017-02-09 80 views
-4

比方說,我們有一些像數組去除數組重複的單詞在PHP

[ 
"red book", 
"red apple", 
"socks", 
"grey socks", 
"red sky", 
"red cross" <----- 4th "red", need to remove this element 
"green cross", 
"blue jeans" 
] 

所以我需要刪除,包含單詞整個陣列中重複3次以上的任何數組元素。因此,導致了上面的例子可能看起來像:

[ 
"red book", 
"red apple", 
"socks", 
"grey socks", 
"red sky", 
"green cross", 
"blue jeans" 
] 

所以單詞「紅」重複超過3陣列倍。我們必須保持排列中的任何單詞出現3次,並刪除其他出現的元素。

在我看來,首先用空間符號衝擊整個數組,然後爆炸成單個單詞。並且使用array_count可能會導致結果。但我無法完成這個想法。

有什麼建議嗎?

+0

爲什麼不添加YOUT PHP代碼?你一直在嘗試什麼? – stweb

+1

匹配僅基於條目的第一個單詞嗎?例如,「簡單的紅色」會被認爲是重複的? – alanlittle

+0

@alanlittle全部單詞 – demonoid

回答

2

你需要寫這樣一個功能:

function fix_array ($array) 
{ 
    $filtered = array(); 
    $word_counts = array(); 

    foreach ($array as $i => $value) 
    { 
     $words = explode(' ', $value); 
     $temp_word_counts = $word_counts; 

     foreach ($words as $word) { 
      if (array_key_exists($word, $temp_word_counts)){ 
       if ($temp_word_counts[$word] == 3){ 
        continue 2; 
       } 
      } 
      else{ 
       $temp_word_counts[$word] = 0; 
      } 

      $temp_word_counts[$word]++; 
     } 

     foreach ($words as $word) { 
      if (!array_key_exists($word, $word_counts)){ 
       $word_counts[$word] = 0; 
      } 
      $word_counts[$word]++; 
     } 

     $filtered[] = $value; 
    } 

    return $filtered; 
} 

$old_array = [ 
    "red book", 
    "red apple", 
    "socks", 
    "grey socks", 
    "red sky", 
    "red cross", 
    "green cross", 
    "blue jeans" 
]; 

$new_array = fix_array($old_array); 
+0

如果您提供了一個工作腳本,並且輸入了一個對您的函數的調用,但它在工作時會對提問者更好+1 – RiggsFolly

1

考慮這個例子:

$arr = array(
     "red book", 
     "red apple", 
     "socks", 
     "grey socks", 
     "red sky", 
     "red cross", 
     "green cross", 
     "blue jeans" 
    ); 
    $used_words = array(); 
    $new_arr = array(); 

    array_walk($arr, function($val) { 
     $matches = array(); 
     preg_match_all('/\b\w+?\b/', $val, $matches); 

     foreach ($matches[0] as $value) { 
      isset($GLOBALS['used_words'][$value]) ? $GLOBALS['used_words'][$value] += 1 : $GLOBALS['used_words'][$value] = 1; 

      if ($GLOBALS['used_words'][$value] > 3) { 
       return; 
      } 
     } 

     $GLOBALS['new_arr'][] = $val; 
    }); 

    print_r($new_arr);