我有一个看起来像这样的数组:
[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]发布于 2017-02-09 16:03:21
所以我试着找出一种没有两个循环的更光滑的方法,但是这样可以做到:
foreach($array as $k => $a) {
foreach($array as $b) {
if(strtolower($a) !== strtolower($b) &&
(strpos(strtolower($b), strtolower($a)) !== false)) {
unset($array[$k]);
}
}
}也许更短一点:
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]);
}
}
}发布于 2017-02-09 16:01:02
试试这个:
<?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 ) );发布于 2017-02-09 16:32:54
这应该会起作用,但是它只会在单词级别上查找匹配项,并且区分大小写。
<?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;
}
}
}https://stackoverflow.com/questions/42141010
复制相似问题