【问题标题】:how to display all the array keys where the values are similars?如何显示值相似的所有数组键?
【发布时间】:2016-03-09 10:02:32
【问题描述】:

我有一个这样的数组:

$array = array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'red', 4 => 'red');

我想显示值相似的所有数组键。

红色 - 3、4

谢谢!

【问题讨论】:

标签: php arrays key


【解决方案1】:

这是实现任务的一种方式(良好的执行时间+良好的内存使用):

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

【讨论】:

    【解决方案2】:

    你可以使用下面的代码

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

    【讨论】:

    • 为什么 OP 应该尝试这个?一个好的答案总是会解释所做的事情以及这样做的原因,不仅适用于 OP,而且适用于 SO 的未来访问者。
    • @JayBlanchard,如果您发现我的想法,我认为答案仍然是比没有答案更好的答案。 :)
    • @JayBlanchard,是的,无法反驳。
    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2013-12-03
    • 1970-01-01
    • 2021-12-25
    • 2020-10-25
    相关资源
    最近更新 更多