dongmeng1868 2016-07-08 11:05
浏览 71
已采纳

PHP在递归数组中移动重复项

I building a translation form that is build using a array filled with the translation keys, to keys are however often duplicated. As the form is builded in group i want to move the duplicates to the $translatables['global'] Note that what you're seeing in the image below is already placed in $translatables['modules']['Module_{{ModuleName}}']

As you can see in the image below, some fields are duplicates. those needs to be moved. The duplicates can be placed accross multiple elements. If the issue isn't clear you can see it here

I edit for the duplicate message: It ain't, its a question to move those values not to filter them (and keep 1 remaining), they need to be placed under a global section.

  • 写回答

1条回答 默认 最新

  • douyasihefu6214 2016-07-08 13:06
    关注

    I solved it myself

    class Tools_Array
    {
        public static function find_duplicates_recursive(&$array, $remove = false)
        {
            $duplicates = array();
    
            $valueCounts = array_count_values(self::array_values_recursive($array));
            foreach ($valueCounts as $key => $value) {
                if ($value > 1)
                {
                    $duplicates[] = $key;
                }
            }
    
            if ($remove) {
                foreach ($duplicates as $duplicate)
                {
                    $array = self::remove_values_recursive($array, $duplicate);
                }
            }
    
            return $duplicates;
        }
    
        public static function array_values_recursive($array)
        {
            $arr2 = array();
            foreach ($array as $key => $value)
            {
                if(is_array($value))
                {
                    $arr2 = array_merge(array_values_recursive($value), $arr2);
                }else{
                    $arr2[] = $value;
                }
            }
    
            return $arr2;
        }
    
        public static function remove_values_recursive($array, $needle)
        {
            foreach ($array as $key => $value)
            {
                if(is_array($value))
                {
                    $array[$key] = self::remove_values_recursive($value, $needle);
                }else{
                    if ($value == $needle)
                    {
                        unset($array[$key]);
                    }
                }
            }
    
            return $array;
        }
    }
    

    Then i can filter it with:

    $duplicates = Tools_Array::find_duplicates_recursive($translatables, true);
    $translatables['globaal'] = array_merge($translatables['globaal'], $duplicates);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?