douyun3022 2015-12-04 12:53
浏览 19

如何显示值类似的所有数组键?

I have a array like this:

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

and I want to display all the array keys where the values are similars.

Red - 3, 4

Thanks!

  • 写回答

2条回答 默认 最新

  • drsc10888 2015-12-04 13:13
    关注

    You can use the below code

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探