2015-06-03 51 views
8

频繁的值所以我有这样的JSON数组:PHP:在阵列

[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数组中。

+0

FYI:您可以接受谁帮助你最,解决你的问题(http://meta.stackexchange.com/q/5234)答案 – Rizier123

+0

如果多个值共享相同的号码出现,做你想要任何,全部或者全部都不是。例如。 '[5,4,2,6,7,3,1]'都有一个事件,你会选择哪一个? – salathe

回答

18
$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, 
) 
+6

'$ this_answer =“美丽”;' –

5

的关键是使用类似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) 

?>