我有一个这样的数组:
$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');
我希望显示值类似的所有数组键。
红色 - 3,4
谢谢!
答案 0 :(得分:0)
您可以使用以下代码
$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');
// temp array to store unique values
$unique_values = array();
// temp array to store duplicate values
$dup_values = array();
// looping through each value in array
foreach($array as $key=>$value)
{
// If the value is not in unique value i am addig it, if it is then its duplicate so i am adding the keys of duplicate value in $dup_values array
if(!in_array($value, $unique_values))
{
$unique_values[] = $value;
}
else
{
$dup_values[$value] = array_keys($array, $value);
}
}
// displaying $dup_values
var_dump($dup_values);
答案 1 :(得分:0)
这是完成任务的一种方法(良好的执行时间+良好的内存使用率):
$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');
$value_keys = array();
$dup_values = array();
// looping through each value in array
foreach($array as $key=>$value)
{
//reduce the array in the format value=>keys
$value_keys[$value][]=$key ;
}
//find the duplicate values
foreach($value_keys as $k=>$v){
if(count($v)>1)
$dup_values[$k]=$v;
unset($value_keys[$k]);//free memory
}
// displaying $dup_values
var_dump($dup_values);
输出:
array(1) {
["red"]=>
array(2) {
[0]=>
int(3)
[1]=>
int(4)
}
}