从逗号分隔的字符串中删除重复项 [英] remove duplicates from comma separated string

查看:356
本文介绍了从逗号分隔的字符串中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好(更快)的解决方案,从逗号分隔的字符串中删除重复的?

  public function d ){
if(strpos($ dep,',')!== false){
$ nd = explode(',',$ dep)
$ oa = array_unique($ nd);
$ nx =(count($ oa)> 1)? implode(,,$ oa):$ oa [0];
}
else {
$ nx = $ dep;
}

return $ nx;非常感谢你们。


h2_lin>解决方案

您可以使用数组键的唯一性:

  function d ){
return implode(',',array_keys(array_flip(explode(',',$ dep))));
}

array_flip 交换键值关联,因此值成为键,反之亦然。这将自动消除重复。其运行时复杂度为O( n )。


Is there a better (faster) solution to remove duplicates from a comma separated string?

public function d($dep) { 
    if (strpos($dep,',') !== false) {
        $nd = explode(',',$dep);
        $oa = array_unique($nd);
        $nx = (count($oa) > 1) ? implode(",",$oa) : $oa[0];
    }
    else {
        $nx = $dep;
    }

    return $nx;
}

Thanks guys.

解决方案

You could use the uniqueness of array keys:

function d($dep) {
    return implode(',', array_keys(array_flip(explode(',', $dep))));
}

array_flip swaps the key-value association, so the values become the keys and vice versa. This will automatically eliminate duplicates. Its runtime complexity is O(n).

这篇关于从逗号分隔的字符串中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆