Find and replace duplicates in Array

后端 未结 4 1084
小蘑菇
小蘑菇 2021-01-13 20:14

I need to make app with will fill array with some random values, but if in array are duplicates my app not working correctly. So I need to write script code which will find

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 20:48

    Here the example how to generate unique values and replace recurring values in array

    function get_unique_val($val, $arr) {
        if ( in_array($val, $arr) ) {
            $d = 2; // initial prefix 
            preg_match("~_([\d])$~", $val, $matches); // check if value has prefix
            $d = $matches ? (int)$matches[1]+1 : $d;  // increment prefix if exists
    
            preg_match("~(.*)_[\d]$~", $val, $matches);
    
            $newval = (in_array($val, $arr)) ? get_unique_val($matches ? $matches[1].'_'.$d : $val.'_'.$d, $arr) : $val;
            return $newval;
        } else {
            return $val;
        }
    }
    
    function unique_arr($arr) {
        $_arr = array();
        foreach ( $arr as $k => $v ) {
            $arr[$k] = get_unique_val($v, $_arr);
            $_arr[$k] = $arr[$k];
        }
        unset($_arr);
    
        return $arr;
    }
    
    
    
    
    $ini_arr = array('dd', 'ss', 'ff', 'nn', 'dd', 'ff', 'vv', 'dd');
    
    $res_arr = unique_arr($ini_arr); //array('dd', 'ss', 'ff', 'nn', 'dd_2', 'ff_2', 'vv', 'dd_3');
    

    Full example you can see here webbystep.ru

提交回复
热议问题