找到PHP数组中最常见的数字

时间:2017-05-14 00:27:07

标签: php arrays

我在PHP中有一个带有重复数字的数组,我想找到最常见的数据,但只有当只有一个时才会找到它。

while (count(array_count_values($arr)) > 1) {
$minim = min(array_count_values($arr));
while ($minim == min(array_count_values($arr))) {
    unset($arr[array_search(array_search(min(array_count_values($arr)), array_count_values($idList)), $arr)]);
    $arr = array_splice($arr, 0, 1);
}
}

在我的代码中,第一个运行直到我在数组中只有一个数字(多次),而第二个运行时我删除了频率较低的数字。 我的问题是我的第二个 min()出现了这个错误:"数组必须包含至少一个元素"。

2 个答案:

答案 0 :(得分:0)

您可以对计数执行array_reduce以查找最大值,但由于array_reduce无法访问可迭代的,因此您必须进行额外的转型。

相反,我建议您从SplMaxHeap

延伸来构建自己的MaxHeap
class MaxHeap extends SplMaxHeap {
  public function compare($a, $b) {
    if (current($a) < current($b))
      return -1;
    elseif (current($a) > current($b))
      return 1;
    else
      return 0;
  }
}

然后我们可以这样使用它 - 答案是[ 7 => 4 ],这意味着: 7 是最常见的数字,显示 4

$heap = new MaxHeap();
foreach (array_count_values($numbers) as $n => $count)
  $heap->insert([$n => $count]);

print_r($heap->top());
// [ 7 => 4 ]

printf("%d is the most common number, appearing %d times",
  key($heap->top()),
  current($heap->top())
);
// 7 is the most common number, appearing 4 times

完整脚本

$numbers = [0, 1, 1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 7, 8, 8, 9];

class MaxHeap extends SplMaxHeap {
  public function compare($a, $b) {
    if (current($a) < current($b))
      return -1;
    elseif (current($a) > current($b))
      return 1;
    else
      return 0;
  }
}

$heap = new MaxHeap();
foreach (array_count_values($numbers) as $n => $count)
  $heap->insert([$n => $count]);

printf("%d is the most common number, appearing %d times",
  key($heap->top()),
  current($heap->top())
);

修订历史记录

我没有意识到PHP的原生array_count_values功能。我删除了更复杂的array_reduce,转而支持这种超级专业功能。谢谢,@ CBroe。

答案 1 :(得分:0)

  

我在PHP中有一个带有重复数字的数组,我想找到最常见的数据,但只有当只有一个时才会找到它。

你的方法似乎相当复杂。

以下是我的表现:

$numbers = [1, 6, 5, 6, 2, 1, 6, 7, 8]; // positive test case
//$numbers = [1, 6, 5, 6, 2, 1, 6, 7, 8, 1];  // negative test case

$count = array_count_values($numbers); // get count of occurrence for each number

arsort($count); // sort by occurrence, descending

$first = key($count); // get key of first element, because that is the/one
                      // of the highest number(s)
$count_first = current($count); // get occurrence for first array value
$count_second = next($count); // get occurrence for second array value

if($count_first != $count_second) { // did they occur in different frequencies?
  echo $first . ' occurred most in input array.';
}
else {
  echo 'input array contained multiple values with highest occurrence.';
}
相关问题