具有最多重复值的关联数组

时间:2014-07-01 18:01:40

标签: php arrays

目前我正在开发一些有趣的东西 - 并且有问题。从来没有过这个。

我有一个关联数组 - 分为4个部分。目标是找到内容最重复的部分:

array(4) {
  ["addition"]=>
  array(3) {
    [1]=>
    int(24)
    [2]=>
    int(12)
    [3]=>
    int(6)
  }
  ["subtraction"]=>
  array(3) {
    [1]=>
    int(8)
    [2]=>
    int(4)
    [3]=>
    int(2)
  }
  ["multiplication"]=>
  array(3) {
    [1]=>
    int(128)
    [2]=>
    int(32)
    [3]=>
    int(8)
  }
  ["division"]=>
  array(3) {
    [1]=>
    int(2)
    [2]=>
    int(2)
    [3]=>
    int(2)
  }
}

这是由以下代码段生成的:

    // Holds the diffs
    $diffContainer = array();

    // Some numbers?
    $numbers = array(16,8,4,2);

    foreach($numbers as $currentNumberLevel => &$number) {
        // There is no difference between zero and the number before
        if($currentNumberLevel === 0) {
            continue;
        }

        // Calculate the diffs
        // > Addition
        $diffContainer['addition'][$currentNumberLevel] = $numbers[($currentNumberLevel - 1)] + $number;
        // > Subtraction
        $diffContainer['subtraction'][$currentNumberLevel] = $numbers[($currentNumberLevel - 1)] - $number;
        // > Multiplication
        $diffContainer['multiplication'][$currentNumberLevel] = $numbers[($currentNumberLevel - 1)] * $number;
        // > Division
        $diffContainer['division'][$currentNumberLevel] = $numbers[($currentNumberLevel - 1)] / $number;
    }

在摘要中,除法部分具有最重复的内容 - 如何用小行代码实现这一点?

3 个答案:

答案 0 :(得分:0)

循环你的主阵列

$dups = array();
foreach($array as $key => $value){
    $dups[$key] = array_count_values($value);
}

然后

$currentHighestValue = 0;
foreach($dups as $type => $value){
    foreach($value as $v){
        if($v > $currentHighestValue){
            $currentHighestValue = $v;
            $currentHighestType = $type;
        }
    }
}

print $currentHighestType; // outputs 'division'

请记住,如果两种类型共享最高重复项,则会报告第一种类型

答案 1 :(得分:0)

您可以在此版本中使用array_count_values()。例如:

$data['most_number_of_dups'] = 0;
$data['key_with_most'] = '';
$data['result_with_most'] = null;
foreach($diffContainer as $key => $values) {
    $dups = array_count_values($values);
    if(reset($dups) > $data['most_number_of_dups']) {
        $data['most_number_of_dups'] = reset($dups);
        $data['key_with_most'] = $key;
        $data['result_with_most'] = key($dups);
    }
}

echo '<pre>';
print_r($data);

应输出:

Array
(
    [most_number_of_dups] => 3
    [key_with_most] => division
    [result_with_most] => 2
)

答案 2 :(得分:-2)

    $diffContainer = array(array(1,1,2,2),array(1,2,2,2),array(3,3,3,3));
    $yuh = array();
    foreach($diffContainer as $k => $v){
      $yuh[$k]=max(array_count_values($v));
    }
    CVarDumper::dump($yuh, 10, true);//array(2,3,4)
    $answer = max(array_keys($yuh, max($yuh)));
    echo '<br>';
    CVarDumper::dump($answer, 10, true);//2