2017-02-09 155 views
0

裏面已經部分存在我有一個數組,看起來像這樣:檢查數組元素的數組

[Amsterdam, Elderly people, Thousand students, Sixteen thousand students, Clean houses] 

正如你可以看到,有一個條目「thousand students」和進入「sixteen thousand students」。有沒有辦法讓我過濾掉thousand students(並刪除此條目),因爲它已經部分存在?

但是,只是手動取消設置元素將無法正常工作。該數組是API的結果,這意味着我不知道是否有部分重複。

謝謝。

編輯:預期結果:

[Amsterdam, Elderly people, Sixteen thousand students, Clean houses] 
+0

你是說你想讓兩個值都對嗎?你能發佈預期的o/p嗎? – rahulsm

+0

@rahul_m不,我想刪除一個。編輯該職位:-) –

+0

意味着千名學生將被刪除,一萬六千名學生將保持正確? – rahulsm

回答

2

所以我試圖找出沒有兩個循環的巧妙方式,但是這將做到這一點:

foreach($array as $k => $a) { 
    foreach($array as $b) { 
     if(strtolower($a) !== strtolower($b) && 
      (strpos(strtolower($b), strtolower($a)) !== false)) { 
      unset($array[$k]); 
     } 
    } 
} 
  • 循環陣列並將每個小寫字母的值與eac進行比較小寫
  • 如果它們不相等,並且一個在另一個內發現,H其它值中使用的密鑰,以除去一個在另一個

也許有一點發現較短:

foreach(array_map('strtolower', $array) as $k => $a) { 
    foreach(array_map('strtolower', $array) as $b) { 
     if($a !== $b && (strpos($b, $a) !== false)) { 
      unset($array[$k]); 
     } 
    } 
} 
0

試試這個:

<?php 
function custom_filter($data) { 
    $data_lc = array_map(function($value){ 
     return strtolower($value); 
    }, $data); 

    foreach ($data_lc as $keyA => $valueA) { 
     foreach ($data_lc as $keyB => $valueB) { 
      if ($keyA === $keyB) { 
       continue; 
      } 
      if (false !== strpos($valueA, $valueB)) { 
       if (strlen($valueA) <= strlen($valueB)) { 
        unset($data[$keyA]); 
       } else { 
        unset($data[$keyB]); 
       } 
      } 
     } 
    } 

    return $data; 
} 

$array = ['Amsterdam', 'Elderly people', 'Thousand students', 'Sixteen thousand students', 'Clean houses']; 
print_r(custom_filter($array)); 
0

這應該可以做到這一點,但它只會在字級查找匹配,並且區分大小寫。

<?php 
$wordsList = [ 
    'Amsterdam', 'Elderly people', 'Thousand students', 
    'Sixteen thousand students', 'Clean houses', 
]; 

$lookup = array(); 
foreach ($wordsList as $k => $words) { 
    $phrase = ''; 
    foreach (preg_split('`\s+`', $words, -1, PREG_SPLIT_NO_EMPTY) as $word) { 
     $phrase .= $word; 

     if (in_array($phrase, $words)) { 
      unset($wordsList[$k]); 
      break; 
     } 
    } 
}