PHP - Make an associative array unique, key -> val

2019-06-28 01:17发布

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 )
)

2条回答
爷、活的狠高调
2楼-- · 2019-06-28 01:49

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.

查看更多
等我变得足够好
3楼-- · 2019-06-28 01:58

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]);
            }
        }
     }
 }
查看更多
登录 后发表回答