首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查数组元素是否已经部分存在于数组中

检查数组元素是否已经部分存在于数组中
EN

Stack Overflow用户
提问于 2017-02-09 15:46:04
回答 3查看 60关注 0票数 0

我有一个看起来像这样的数组:

代码语言:javascript
复制
[Amsterdam, Elderly people, Thousand students, Sixteen thousand students, Clean houses]

如您所见,有一个条目"thousand students“和一个条目"sixteen thousand students”。是否有一种方法可以让我过滤掉thousand students (并删除这个条目),因为它已经部分存在?

但是,仅仅手动取消元素是行不通的。数组是API的结果,这意味着我不知道是否有部分重复。

谢谢。

编辑:预期结果:

代码语言:javascript
复制
[Amsterdam, Elderly people, Sixteen thousand students, Clean houses]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-02-09 16:03:21

所以我试着找出一种没有两个循环的更光滑的方法,但是这样可以做到:

代码语言:javascript
复制
foreach($array as $k => $a) {
    foreach($array as $b) {
        if(strtolower($a) !== strtolower($b) &&
          (strpos(strtolower($b), strtolower($a)) !== false)) {
            unset($array[$k]);
        }
    }
}
  • 循环数组,并将小写的每个值与小写的每个值进行比较。
  • 如果它们不相等,并且在另一个中找到一个,则使用键移除另一个中的一个。

也许更短一点:

代码语言:javascript
复制
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]);
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2017-02-09 16:01:02

试试这个:

代码语言:javascript
复制
<?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
EN

Stack Overflow用户

发布于 2017-02-09 16:32:54

这应该会起作用,但是它只会在单词级别上查找匹配项,并且区分大小写。

代码语言:javascript
复制
<?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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42141010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档