PHP - Make an associative array unique, key -> value and value -> key

放肆的年华 提交于 2019-12-10 17:39:27

问题


I have a little problem in php, which i find hard to explain in words. I have an associative array which contains key-value. I would like to make a function (or if there is already one) which would take an array as input and remove the duplicates but both ways.

For example:

In my array I have {a -> b} {a -> c} {b -> a} {b -> c} ...

From this view it does not seem like there is any duplicate, but to me {a -> b} and {b -> a} are duplicate. So I would like the function to see it as a duplicate and only return one of them.

I tried to use array_flip / array_unique to exchange the key and the values, in a loop but didn't quite work.

Could you help to find a way to do this even if it is array with a large length? or if there is a php function which does it.

Help would be really appreciated, thanks.


There is code to illustrate the idea:

For an array which would be like that:

Array ( 
    [0] => Array ( [0] => a [1] => b)
    [1] => Array ( [0] => a [1] => c )
    [2] => Array ( [0] => b [1] => a )
    [3] => Array ( [0] => b [1] => c )
)

回答1:


This will remove your dublicates

foreach($array as $key => $value){
     if (isset($array[$key])){
        if(isset($array[$value])){
            if($array[$value] == $key){
                unset($array[$value]);
            }
        }
     }
 }



回答2:


This should work:

function cleanArray($array)
{
   $newArray = array();
   foreach ($array as $key => $val) {
      if (isset($array[$val]) && $array[$val] == $key) {
         if (!isset($newArray[$key]) && !isset($newArray[$val])) {
            $newArray[$key] = $val; 
         }      
         unset($array[$key], $array[$val]);
      }
   }    
   return array_merge($array, $newArray);
}

Working example here.



来源:https://stackoverflow.com/questions/15040084/php-make-an-associative-array-unique-key-value-and-value-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!