PHP:数组中最常见的值

时间:2015-06-03 17:24:53

标签: php arrays json repeat

所以我有这个JSON数组:

[0] => 238
[1] => 7
[2] => 86
[3] => 79
[4] => 55
[5] => 92
[6] => 55
[7] => 7
[8] => 254
[9] => 9
[10] => 75
[11] => 238
[12] => 89
[13] => 238

我将在实际的JSON文件中拥有更多值。但通过观察,我可以看到238和55的重复次数超过任何其他数字。我想要做的是获取数组中前5个最重复的值并将它们存储在新的PHP数组中。

2 个答案:

答案 0 :(得分:31)

$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);

Demo

$array = [1,2,3,4,238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);

array (
  0 => 238,
  1 => 55,
  2 => 7,
  3 => 4,
  4 => 3,
)

答案 1 :(得分:6)

关键是使用类似array_count_values()的内容来计算每个值的出现次数。

<?php

$array = [238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];

// Get array of (value => count) pairs, sorted by descending count
$counts = array_count_values($array);
arsort($counts);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1, 9 => 1, ...)

// An array with the first (top) 5 counts
$top_with_count = array_slice($counts, 0, 5, true);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1)

// An array with just the values
$top = array_keys($top_with_count);
// array(238, 55, 7, 75, 89)

?>