PHP-使关联数组唯一,键->价值和价值->钥匙 [英] PHP - Make an associative array unique, key -> value and value -> key
问题描述
我在php中有一个小问题,我很难用语言来解释.我有一个包含键值的关联数组.我想制作一个函数(或者如果已经有一个函数),该函数将数组作为输入并删除重复项,但是两种方式都可以.
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.
例如:
在我的数组中,我有{a-> b} {a-> c} {b-> a} {b-> c} ...
In my array I have {a -> b} {a -> c} {b -> a} {b -> c} ...
从这个角度看,似乎没有任何重复,但是对我来说{a-> b}和{b-> a}是重复的.因此,我希望函数将其视为重复项,并且只返回其中之一.
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.
我试图在循环中使用array_flip/array_unique交换键和值,但效果不佳.
I tried to use array_flip / array_unique to exchange the key and the values, in a loop but didn't quite work.
即使数组长度很大,您能帮忙找到一种方法吗?或是否有执行此功能的php函数.
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.
非常感谢您的帮助.
有代码可以说明这个想法:
There is code to illustrate the idea:
对于这样的数组:
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 )
)
推荐答案
这将删除您的重复项
foreach($array as $key => $value){
if (isset($array[$key])){
if(isset($array[$value])){
if($array[$value] == $key){
unset($array[$value]);
}
}
}
}
这篇关于PHP-使关联数组唯一,键->价值和价值->钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!